hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 958k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f72c0bf5b4bcb72b7e7dd97debcab75606cc1e94 | 4,894 | py | Python | Widgets/openGL_widgets/VectorGLContext.py | qftphys/Software-for-visualising-magnetic-layers | 7e4c5680b8e87aa677bdf4c912cbccdcb11b09a3 | [
"MIT"
] | null | null | null | Widgets/openGL_widgets/VectorGLContext.py | qftphys/Software-for-visualising-magnetic-layers | 7e4c5680b8e87aa677bdf4c912cbccdcb11b09a3 | [
"MIT"
] | null | null | null | Widgets/openGL_widgets/VectorGLContext.py | qftphys/Software-for-visualising-magnetic-layers | 7e4c5680b8e87aa677bdf4c912cbccdcb11b09a3 | [
"MIT"
] | null | null | null | from PyQt5.QtWidgets import QWidget
from Widgets.openGL_widgets.AbstractGLContext import AbstractGLContext
from ColorPolicy import ColorPolicy
from ctypes import c_void_p
from PyQt5.Qt import Qt
from PyQt5.QtCore import QPoint, QThread
from cython_modules.color_policy import multi_iteration_normalize
from pattern_types.Patterns import AbstractGLContextDecorators
import numpy as np
import OpenGL.GLU as glu
import OpenGL.GL as gl
import math as mt
from multiprocessing import Pool
from ColorPolicy import ColorPolicy
class VectorGLContext(AbstractGLContext, QWidget):
def __init__(self, data_dict):
super().__init__()
super().shareData(**data_dict)
self.prerendering_calculation()
# self.drawing_function = self.slow_arrow_draw
self.drawing_function = self.vbo_arrow_draw
def prerendering_calculation(self):
super().prerendering_calculation()
if self.normalize:
VectorGLContext.normalize_specification(self.color_vectors, vbo=True)
self.interleaved = ColorPolicy.apply_vbo_interleave_format(self.vectors_list,
self.color_vectors)
self.buffers = None
## pad the color
self.color_vectors = ColorPolicy.apply_vbo_format(self.color_vectors, k=2)
self.color_vertices = len(self.vectors_list)
self.vertices = self.color_vertices*2
self.color_buffer_len = len(self.color_vectors[0])*4
self.inter_buffer_len = len(self.interleaved[0])*4
self.__FLOAT_BYTE_SIZE__ = 8
@AbstractGLContextDecorators.recording_decorator
def slow_arrow_draw(self):
gl.glLineWidth(2*self.scale)
gl.glPointSize(3*self.scale)
for vector, color in zip(self.vectors_list,
self.color_vectors[self.i]):
if not np.any(color):
continue
self.base_arrow(vector, color)
def base_arrow(self, vector, color):
gl.glColor3f(*color)
gl.glBegin(gl.GL_LINES)
gl.glVertex3f(*vector)
gl.glVertex3f(vector[0]+color[0], vector[1]+color[1],
vector[2]+color[2])
gl.glEnd()
gl.glBegin(gl.GL_POINTS)
gl.glVertex3f(vector[0]+color[0], vector[1]+color[1],
vector[2]+color[2])
gl.glEnd()
def standard_vbo_draw(self):
gl.glEnableClientState(gl.GL_COLOR_ARRAY)
gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glColorPointer(3, gl.GL_FLOAT, 0, None)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
gl.glVertexPointer(3, gl.GL_FLOAT, 0, None)
gl.glDrawArrays(gl.GL_LINES, 0, int(self.vertices))
# now the points
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glColorPointer(3, gl.GL_FLOAT, 3*self.__FLOAT_BYTE_SIZE__, None)
# stride is 3 bytes (3 floats) VVVCCCVVVCCC etc...
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
# offset is at 3 indices, so points at 4th vector 3(vertices)*4
gl.glVertexPointer(3, gl.GL_FLOAT, 3*self.__FLOAT_BYTE_SIZE__,
c_void_p(4*3))
gl.glDrawArrays(gl.GL_POINTS, 0, int(self.color_vertices))
gl.glDisableClientState(gl.GL_COLOR_ARRAY)
gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
def vbo_arrow_draw(self):
if self.buffers is None:
self.buffers = self.create_vbo()
else:
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, self.inter_buffer_len,
np.array(self.interleaved[self.i],
dtype='float32').flatten())
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, self.color_buffer_len,
np.array(self.color_vectors[self.i],
dtype='float32').flatten())
self.standard_vbo_draw()
def create_vbo(self):
buffers = gl.glGenBuffers(2)
gl.glLineWidth(2*self.scale)
gl.glPointSize(3*self.scale)
# vertices buffer
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffers[0])
gl.glBufferData(gl.GL_ARRAY_BUFFER,
np.array(self.interleaved[self.i],
dtype='float32').flatten(),
gl.GL_DYNAMIC_DRAW)
# color buffer
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffers[1])
gl.glBufferData(gl.GL_ARRAY_BUFFER,
np.array(self.color_vectors[self.i],
dtype='float32').flatten(),
gl.GL_DYNAMIC_DRAW)
return buffers
| 38.84127 | 86 | 0.626481 | from PyQt5.QtWidgets import QWidget
from Widgets.openGL_widgets.AbstractGLContext import AbstractGLContext
from ColorPolicy import ColorPolicy
from ctypes import c_void_p
from PyQt5.Qt import Qt
from PyQt5.QtCore import QPoint, QThread
from cython_modules.color_policy import multi_iteration_normalize
from pattern_types.Patterns import AbstractGLContextDecorators
import numpy as np
import OpenGL.GLU as glu
import OpenGL.GL as gl
import math as mt
from multiprocessing import Pool
from ColorPolicy import ColorPolicy
class VectorGLContext(AbstractGLContext, QWidget):
def __init__(self, data_dict):
super().__init__()
super().shareData(**data_dict)
self.prerendering_calculation()
self.drawing_function = self.vbo_arrow_draw
def prerendering_calculation(self):
super().prerendering_calculation()
if self.normalize:
VectorGLContext.normalize_specification(self.color_vectors, vbo=True)
self.interleaved = ColorPolicy.apply_vbo_interleave_format(self.vectors_list,
self.color_vectors)
self.buffers = None
olor_vectors = ColorPolicy.apply_vbo_format(self.color_vectors, k=2)
self.color_vertices = len(self.vectors_list)
self.vertices = self.color_vertices*2
self.color_buffer_len = len(self.color_vectors[0])*4
self.inter_buffer_len = len(self.interleaved[0])*4
self.__FLOAT_BYTE_SIZE__ = 8
@AbstractGLContextDecorators.recording_decorator
def slow_arrow_draw(self):
gl.glLineWidth(2*self.scale)
gl.glPointSize(3*self.scale)
for vector, color in zip(self.vectors_list,
self.color_vectors[self.i]):
if not np.any(color):
continue
self.base_arrow(vector, color)
def base_arrow(self, vector, color):
gl.glColor3f(*color)
gl.glBegin(gl.GL_LINES)
gl.glVertex3f(*vector)
gl.glVertex3f(vector[0]+color[0], vector[1]+color[1],
vector[2]+color[2])
gl.glEnd()
gl.glBegin(gl.GL_POINTS)
gl.glVertex3f(vector[0]+color[0], vector[1]+color[1],
vector[2]+color[2])
gl.glEnd()
def standard_vbo_draw(self):
gl.glEnableClientState(gl.GL_COLOR_ARRAY)
gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glColorPointer(3, gl.GL_FLOAT, 0, None)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
gl.glVertexPointer(3, gl.GL_FLOAT, 0, None)
gl.glDrawArrays(gl.GL_LINES, 0, int(self.vertices))
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glColorPointer(3, gl.GL_FLOAT, 3*self.__FLOAT_BYTE_SIZE__, None)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
gl.glVertexPointer(3, gl.GL_FLOAT, 3*self.__FLOAT_BYTE_SIZE__,
c_void_p(4*3))
gl.glDrawArrays(gl.GL_POINTS, 0, int(self.color_vertices))
gl.glDisableClientState(gl.GL_COLOR_ARRAY)
gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
def vbo_arrow_draw(self):
if self.buffers is None:
self.buffers = self.create_vbo()
else:
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, self.inter_buffer_len,
np.array(self.interleaved[self.i],
dtype='float32').flatten())
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, self.color_buffer_len,
np.array(self.color_vectors[self.i],
dtype='float32').flatten())
self.standard_vbo_draw()
def create_vbo(self):
buffers = gl.glGenBuffers(2)
gl.glLineWidth(2*self.scale)
gl.glPointSize(3*self.scale)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffers[0])
gl.glBufferData(gl.GL_ARRAY_BUFFER,
np.array(self.interleaved[self.i],
dtype='float32').flatten(),
gl.GL_DYNAMIC_DRAW)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffers[1])
gl.glBufferData(gl.GL_ARRAY_BUFFER,
np.array(self.color_vectors[self.i],
dtype='float32').flatten(),
gl.GL_DYNAMIC_DRAW)
return buffers
| true | true |
f72c0c49d7421b18eade26ce7db864b767a81dcd | 6,768 | py | Python | tests/infra/runner.py | iLuSIAnn/test | 10d0a20dc1a646b5c1f6c7bff2960e3f5df0510e | [
"Apache-2.0"
] | null | null | null | tests/infra/runner.py | iLuSIAnn/test | 10d0a20dc1a646b5c1f6c7bff2960e3f5df0510e | [
"Apache-2.0"
] | null | null | null | tests/infra/runner.py | iLuSIAnn/test | 10d0a20dc1a646b5c1f6c7bff2960e3f5df0510e | [
"Apache-2.0"
] | null | null | null | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache 2.0 License.
import getpass
import time
import http
import logging
from random import seed
import infra.network
import infra.proc
import infra.remote_client
import infra.rates
import cimetrics.upload
from loguru import logger as LOG
logging.getLogger("matplotlib").setLevel(logging.WARNING)
logging.getLogger("paramiko").setLevel(logging.WARNING)
def minimum_number_of_local_nodes(args):
"""
If we are using bft then we need to have 3 nodes. CFT will run with 1 nodes, unless it expects a backup
"""
if args.consensus == "bft":
return 3
if args.send_tx_to == "backups":
return 2
return 1
def get_command_args(args, get_command):
command_args = []
return get_command(*command_args)
def filter_nodes(primary, backups, filter_type):
if filter_type == "primary":
return [primary]
elif filter_type == "backups":
if not backups:
raise Exception("--send-tx-to backups but no backup was found")
return backups
else:
return [primary] + backups
def configure_remote_client(args, client_id, client_host, node, command_args):
if client_host == "localhost":
client_host = infra.net.expand_localhost()
remote_impl = infra.remote.LocalRemote
else:
remote_impl = infra.remote.SSHRemote
try:
remote_client = infra.remote_client.CCFRemoteClient(
"client_" + str(client_id),
client_host,
args.client,
node.host,
node.rpc_port,
args.workspace,
args.label,
args.config,
command_args,
remote_impl,
)
remote_client.setup()
return remote_client
except Exception:
LOG.exception("Failed to start client {}".format(client_host))
raise
def run(get_command, args):
if args.fixed_seed:
seed(getpass.getuser())
hosts = args.nodes
if not hosts:
hosts = ["local://localhost"] * minimum_number_of_local_nodes(args)
LOG.info("Starting nodes on {}".format(hosts))
with infra.network.network(
hosts, args.binary_dir, args.debug_nodes, args.perf_nodes, pdb=args.pdb
) as network:
network.start_and_join(args)
primary, backups = network.find_nodes()
command_args = get_command_args(args, get_command)
nodes_to_send_to = filter_nodes(primary, backups, args.send_tx_to)
clients = []
client_hosts = []
if args.one_client_per_backup:
if not backups:
raise Exception(
"--one-client-per-backup was set but no backup was found"
)
client_hosts = ["localhost"] * len(backups)
else:
if args.client_nodes:
client_hosts.extend(args.client_nodes)
if args.num_localhost_clients:
client_hosts.extend(["localhost"] * int(args.num_localhost_clients))
if not client_hosts:
client_hosts = ["localhost"]
for client_id, client_host in enumerate(client_hosts):
node = nodes_to_send_to[client_id % len(nodes_to_send_to)]
remote_client = configure_remote_client(
args, client_id, client_host, node, command_args
)
clients.append(remote_client)
if args.network_only:
for remote_client in clients:
LOG.info(f"Client can be run with: {remote_client.remote.get_cmd()}")
while True:
time.sleep(60)
else:
for remote_client in clients:
remote_client.start()
hard_stop_timeout = 90
try:
with cimetrics.upload.metrics(complete=False) as metrics:
tx_rates = infra.rates.TxRates(primary)
start_time = time.time()
while True:
stop_waiting = True
for i, remote_client in enumerate(clients):
done = remote_client.check_done()
# all the clients need to be done
LOG.info(
f"Client {i} has {'completed' if done else 'not completed'} running ({time.time() - start_time:.2f}s / {hard_stop_timeout}s)"
)
stop_waiting = stop_waiting and done
if stop_waiting:
break
if time.time() > start_time + hard_stop_timeout:
raise TimeoutError(
f"Client still running after {hard_stop_timeout}s"
)
time.sleep(5)
tx_rates.get_metrics()
for remote_client in clients:
perf_result = remote_client.get_result()
LOG.success(f"{args.label}/{remote_client.name}: {perf_result}")
# TODO: Only results for first client are uploaded
# https://github.com/microsoft/CCF/issues/1046
if remote_client == clients[0]:
LOG.success(f"Uploading results for {remote_client.name}")
metrics.put(args.label, perf_result)
else:
LOG.warning(f"Skipping upload for {remote_client.name}")
primary, _ = network.find_primary()
with primary.client() as nc:
r = nc.get("/node/memory")
assert r.status_code == http.HTTPStatus.OK.value
results = r.body.json()
tx_rates.insert_metrics(**results)
# Construct name for heap metric, removing ^ suffix if present
heap_peak_metric = f"Mem_{args.label}"
if heap_peak_metric.endswith("^"):
heap_peak_metric = heap_peak_metric[:-1]
peak_value = results["peak_allocated_heap_size"]
metrics.put(heap_peak_metric, peak_value)
LOG.info(f"Rates:\n{tx_rates}")
tx_rates.save_results(args.metrics_file)
for remote_client in clients:
remote_client.stop()
except Exception:
LOG.error("Stopping clients due to exception")
for remote_client in clients:
remote_client.stop()
raise
| 35.067358 | 157 | 0.553783 |
import getpass
import time
import http
import logging
from random import seed
import infra.network
import infra.proc
import infra.remote_client
import infra.rates
import cimetrics.upload
from loguru import logger as LOG
logging.getLogger("matplotlib").setLevel(logging.WARNING)
logging.getLogger("paramiko").setLevel(logging.WARNING)
def minimum_number_of_local_nodes(args):
if args.consensus == "bft":
return 3
if args.send_tx_to == "backups":
return 2
return 1
def get_command_args(args, get_command):
command_args = []
return get_command(*command_args)
def filter_nodes(primary, backups, filter_type):
if filter_type == "primary":
return [primary]
elif filter_type == "backups":
if not backups:
raise Exception("--send-tx-to backups but no backup was found")
return backups
else:
return [primary] + backups
def configure_remote_client(args, client_id, client_host, node, command_args):
if client_host == "localhost":
client_host = infra.net.expand_localhost()
remote_impl = infra.remote.LocalRemote
else:
remote_impl = infra.remote.SSHRemote
try:
remote_client = infra.remote_client.CCFRemoteClient(
"client_" + str(client_id),
client_host,
args.client,
node.host,
node.rpc_port,
args.workspace,
args.label,
args.config,
command_args,
remote_impl,
)
remote_client.setup()
return remote_client
except Exception:
LOG.exception("Failed to start client {}".format(client_host))
raise
def run(get_command, args):
if args.fixed_seed:
seed(getpass.getuser())
hosts = args.nodes
if not hosts:
hosts = ["local://localhost"] * minimum_number_of_local_nodes(args)
LOG.info("Starting nodes on {}".format(hosts))
with infra.network.network(
hosts, args.binary_dir, args.debug_nodes, args.perf_nodes, pdb=args.pdb
) as network:
network.start_and_join(args)
primary, backups = network.find_nodes()
command_args = get_command_args(args, get_command)
nodes_to_send_to = filter_nodes(primary, backups, args.send_tx_to)
clients = []
client_hosts = []
if args.one_client_per_backup:
if not backups:
raise Exception(
"--one-client-per-backup was set but no backup was found"
)
client_hosts = ["localhost"] * len(backups)
else:
if args.client_nodes:
client_hosts.extend(args.client_nodes)
if args.num_localhost_clients:
client_hosts.extend(["localhost"] * int(args.num_localhost_clients))
if not client_hosts:
client_hosts = ["localhost"]
for client_id, client_host in enumerate(client_hosts):
node = nodes_to_send_to[client_id % len(nodes_to_send_to)]
remote_client = configure_remote_client(
args, client_id, client_host, node, command_args
)
clients.append(remote_client)
if args.network_only:
for remote_client in clients:
LOG.info(f"Client can be run with: {remote_client.remote.get_cmd()}")
while True:
time.sleep(60)
else:
for remote_client in clients:
remote_client.start()
hard_stop_timeout = 90
try:
with cimetrics.upload.metrics(complete=False) as metrics:
tx_rates = infra.rates.TxRates(primary)
start_time = time.time()
while True:
stop_waiting = True
for i, remote_client in enumerate(clients):
done = remote_client.check_done()
LOG.info(
f"Client {i} has {'completed' if done else 'not completed'} running ({time.time() - start_time:.2f}s / {hard_stop_timeout}s)"
)
stop_waiting = stop_waiting and done
if stop_waiting:
break
if time.time() > start_time + hard_stop_timeout:
raise TimeoutError(
f"Client still running after {hard_stop_timeout}s"
)
time.sleep(5)
tx_rates.get_metrics()
for remote_client in clients:
perf_result = remote_client.get_result()
LOG.success(f"{args.label}/{remote_client.name}: {perf_result}")
if remote_client == clients[0]:
LOG.success(f"Uploading results for {remote_client.name}")
metrics.put(args.label, perf_result)
else:
LOG.warning(f"Skipping upload for {remote_client.name}")
primary, _ = network.find_primary()
with primary.client() as nc:
r = nc.get("/node/memory")
assert r.status_code == http.HTTPStatus.OK.value
results = r.body.json()
tx_rates.insert_metrics(**results)
heap_peak_metric = f"Mem_{args.label}"
if heap_peak_metric.endswith("^"):
heap_peak_metric = heap_peak_metric[:-1]
peak_value = results["peak_allocated_heap_size"]
metrics.put(heap_peak_metric, peak_value)
LOG.info(f"Rates:\n{tx_rates}")
tx_rates.save_results(args.metrics_file)
for remote_client in clients:
remote_client.stop()
except Exception:
LOG.error("Stopping clients due to exception")
for remote_client in clients:
remote_client.stop()
raise
| true | true |
f72c0cf297fb6c440eea6a74e7fd555334feff9a | 558 | py | Python | src/Product.py | AbdulMutakabbir/CCH-manufacturing-facility-simulator | ffc1b294eecf69c940b04bfc3d66ef58c7b63de6 | [
"MIT"
] | null | null | null | src/Product.py | AbdulMutakabbir/CCH-manufacturing-facility-simulator | ffc1b294eecf69c940b04bfc3d66ef58c7b63de6 | [
"MIT"
] | null | null | null | src/Product.py | AbdulMutakabbir/CCH-manufacturing-facility-simulator | ffc1b294eecf69c940b04bfc3d66ef58c7b63de6 | [
"MIT"
] | null | null | null | # holds the data and methods for products
class Product:
__type: int = None # specifies P1 or P2
# Constructor:
# Inputs:
# p_type:int -> Product Type
def __init__(self, p_type):
if (p_type is not None) and (p_type >= 0) and (p_type <= 3):
self.__type = p_type
else:
raise Exception("ProductTypeError")
# returns the product type
def get_type(self):
if self.__type is None:
raise Exception("NotInitializedProduct")
else:
return self.__type
| 26.571429 | 68 | 0.586022 |
class Product:
__type: int = None
def __init__(self, p_type):
if (p_type is not None) and (p_type >= 0) and (p_type <= 3):
self.__type = p_type
else:
raise Exception("ProductTypeError")
def get_type(self):
if self.__type is None:
raise Exception("NotInitializedProduct")
else:
return self.__type
| true | true |
f72c0d36cca4aa60ffe71a6c3374a1be477a7388 | 21,847 | py | Python | universe/rewarder/rewarder_session.py | BitJetKit/universe | cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c | [
"MIT"
] | 8,120 | 2016-12-05T06:37:45.000Z | 2022-03-21T14:45:20.000Z | universe/rewarder/rewarder_session.py | BitJetKit/universe | cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c | [
"MIT"
] | 213 | 2016-12-05T09:57:37.000Z | 2018-04-05T18:55:14.000Z | universe/rewarder/rewarder_session.py | BitJetKit/universe | cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c | [
"MIT"
] | 1,140 | 2016-12-05T06:50:43.000Z | 2022-03-23T08:28:32.000Z | from autobahn.twisted import websocket
import logging
import numpy as np
import threading
import time
from twisted.python import failure
from twisted.internet import defer, endpoints
import twisted.internet.error
from universe import utils
from universe.twisty import reactor
from universe.rewarder import connection_timer, env_status, reward_buffer, rewarder_client
from universe.utils import display
logger = logging.getLogger(__name__)
extra_logger = logging.getLogger('universe.extra.'+__name__)
def _ping(client):
return client.send('v0.control.ping', {}, expect_reply=True)
class RewarderSession(object):
def __init__(self):
self.lock = threading.RLock()
self.i = 0
# Mutated by main thread exclusively
self.names_by_id = {}
self.reward_buffers = {}
self.env_statuses = {}
self.errors = {}
self.networks = {}
self.clients = {}
def close(self, name=None, reason=u'closed by RewarderSession.close'):
if name is None:
names = list(self.names_by_id.values())
else:
logger.info('[%s] Closing rewarder connection', name)
names = [name]
self.ids_by_name = {name: id for id, name in self.names_by_id.items()}
for name in names:
with self.lock:
id = self.ids_by_name.pop(name, None)
if id is None:
# already closed
continue
del self.names_by_id[id]
del self.reward_buffers[id]
del self.env_statuses[id]
self.errors.pop(id, None)
network = self.networks.pop(id)
network.close()
client = self.clients.pop(id, None)
if client is not None:
reactor.callFromThread(client.close, reason=reason)
def connect(self, name, address, label, password, env_id=None, seed=None, fps=60,
start_timeout=None, observer=False, skip_network_calibration=False):
if name in self.reward_buffers:
self.close(name, reason='closing previous connection to reconnect with the same name')
network = Network()
self.names_by_id[self.i] = name
self.reward_buffers[self.i] = reward_buffer.RewardBuffer(label)
self.env_statuses[self.i] = env_status.EnvStatus(label=label, primary=False)
self.networks[self.i] = network
reactor.callFromThread(self._connect,
name=name,
address=address,
env_id=env_id,
seed=seed,
fps=fps,
i=self.i,
network=network,
env_status=self.env_statuses[self.i],
reward_buffer=self.reward_buffers[self.i],
label=label,
start_timeout=start_timeout,
password=password,
observer=observer,
skip_network_calibration=skip_network_calibration,
)
self.i += 1
return network
def _already_closed(self, i):
# Lock must be held
return i not in self.names_by_id
# Call only from Twisted thread
# TODO: probably time to convert to kwargs
@defer.inlineCallbacks
def _connect(self, name, address, env_id, seed, fps, i, network, env_status, reward_buffer,
label, password, start_timeout,
observer, skip_network_calibration,
attempt=0, elapsed_sleep_time=0,
):
endpoint = endpoints.clientFromString(reactor, 'tcp:'+address)
factory = websocket.WebSocketClientFactory('ws://'+address)
factory.protocol = rewarder_client.RewarderClient
assert password, "Missing password: {} for rewarder session".format(password)
factory.headers = {'authorization': utils.basic_auth_encode(password), 'openai-observer': 'true' if observer else 'false'}
factory.i = i
# Various important objects
factory.endpoint = endpoint
factory.env_status = env_status
factory.reward_buffer = reward_buffer
# Helpful strings
factory.label = label
factory.address = address
# Arguments to always send to the remote reset call
factory.arg_env_id = env_id
factory.arg_fps = fps
def record_error(e):
if isinstance(e, failure.Failure):
e = e.value
# logger.error('[%s] Recording rewarder error: %s', factory.label, e)
with self.lock:
# drop error on the floor if we're already closed
if self._already_closed(factory.i):
extra_logger.info('[%s] Ignoring error for already closed connection: %s', label, e)
elif factory.i not in self.clients:
extra_logger.info('[%s] Received error for connection which has not been fully initialized: %s', label, e)
# We could handle this better, but right now we
# just mark this as a fatal error for the
# backend. Often it actually is.
self.errors[factory.i] = e
else:
extra_logger.info('[%s] Recording fatal error for connection: %s', label, e)
self.errors[factory.i] = e
def retriable_error(e, error_message):
if isinstance(e, failure.Failure):
e = e.value
if self._already_closed(factory.i):
logger.error('[%s] Got error, but giving up on reconnecting, since %d already disconnected', factory.label, factory.i)
return
# Also need to handle DNS errors, so let's just handle everything for now.
#
# reason.trap(twisted.internet.error.ConnectError, error.ConnectionError)
if elapsed_sleep_time < start_timeout:
sleep = min((2 * attempt+1), 10)
logger.error('[%s] Waiting on rewarder: %s. Retry in %ds (slept %ds/%ds): %s', factory.label, error_message, sleep, elapsed_sleep_time, start_timeout, e)
reactor.callLater(
sleep, self._connect, name=name, address=address,
env_id=env_id, seed=seed, fps=fps, i=i, network=network,
env_status=env_status, reward_buffer=reward_buffer, label=label,
attempt=attempt+1, elapsed_sleep_time=elapsed_sleep_time+sleep,
start_timeout=start_timeout, password=password,
observer=observer, skip_network_calibration=skip_network_calibration,
)
else:
logger.error('[%s] %s. Retries exceeded (slept %ds/%ds): %s', factory.label, error_message, elapsed_sleep_time, start_timeout, e)
record_error(e)
factory.record_error = record_error
try:
retry_msg = 'establish rewarder TCP connection'
client = yield endpoint.connect(factory)
extra_logger.info('[%s] Rewarder TCP connection established', factory.label)
retry_msg = 'complete WebSocket handshake'
yield client.waitForWebsocketConnection()
extra_logger.info('[%s] Websocket client successfully connected', factory.label)
if not skip_network_calibration:
retry_msg = 'run network calibration'
yield network.calibrate(client)
extra_logger.info('[%s] Network calibration complete', factory.label)
retry_msg = ''
if factory.arg_env_id is not None:
# We aren't picky about episode ID: we may have
# already receieved an env.describe message
# telling us about a resetting environment, which
# we don't need to bump post.
#
# tl;dr hardcoding 0.0 here avoids a double reset.
reply = yield self._send_env_reset(client, seed=seed, episode_id='0')
else:
# No env_id requested, so we just proceed without a reset
reply = None
# We're connected and have measured the
# network. Mark everything as ready to go.
with self.lock:
if factory.i not in self.names_by_id:
# ID has been popped!
logger.info('[%s] Rewarder %d started, but has already been closed', factory.label, factory.i)
client.close(reason='RewarderSession: double-closing, client was closed while RewarderSession was starting')
elif reply is None:
logger.info('[%s] Attached to running environment without reset', factory.label)
else:
context, req, rep = reply
logger.info('[%s] Initial reset complete: episode_id=%s', factory.label, rep['headers']['episode_id'])
self.clients[factory.i] = client
except Exception as e:
if retry_msg:
retriable_error(e, 'failed to ' + retry_msg)
else:
record_error(e)
def pop_errors(self):
errors = {}
with self.lock:
if self.errors:
for i, error in self.errors.items():
name = self.names_by_id[i]
errors[name] = error
self.errors.clear()
return errors
def reset(self, seed=None, env_id=None):
with self.lock:
for i, reward_buffer in self.reward_buffers.items():
reward_buffer.mask()
reactor.callFromThread(self._reset, seed=seed, env_id=env_id)
def _reset(self, seed=None, env_id=None):
with self.lock:
for client in self.clients.values():
d = self._send_env_reset(client, seed=seed, env_id=env_id)
# Total hack to capture the variable in the closure
def callbacks(client):
def success(reply): pass
def fail(reason): client.factory.record_error(reason)
return success, fail
success, fail = callbacks(client)
d.addCallback(success)
d.addErrback(fail)
def _send_env_reset(self, client, seed=None, episode_id=None, env_id=None):
if episode_id is None:
episode_id = client.factory.env_status.episode_id
logger.info('[%s] Sending reset for env_id=%s fps=%s episode_id=%s', client.factory.label, client.factory.arg_env_id, client.factory.arg_fps, episode_id)
return client.send_reset(
env_id=client.factory.arg_env_id if env_id is None else env_id,
seed=seed,
fps=client.factory.arg_fps,
episode_id=episode_id)
def pop(self, warn=True, peek_d=None):
reward_d = {}
done_d = {}
info_d = {}
err_d = self.pop_errors()
for i, reward_buffer in self.reward_buffers.items():
name = self.names_by_id[i]
reward, done, info = reward_buffer.pop(peek_d.get(name))
reward_d[name] = reward
done_d[name] = done
info_d[name] = info
# TODO: use FPS here rather than 60
if warn and any(info.get('stats.reward.count', 0) > 60 for info in info_d.values()):
logger.warn('WARNING: returning more than 60 aggregated rewards: %s. Either your agent is not keeping up with the framerate, or you should have called ".reset()" to clear pending rewards and reset the environments to a known state.',
{name: '{} (episode_id={})'.format(info['stats.reward.count'], info.get('env_status.episode_id')) for name, info in info_d.items()})
return reward_d, done_d, info_d, err_d
def wait(self, timeout=None):
deadline = time.time() + timeout
for client in self.clients:
if timeout is not None:
remaining_timeout = deadline - time.time()
else:
remaining_timeout = None
client.reward_buffer.wait_for_step(timeout=remaining_timeout)
# Hack to test actions over websockets
# TODO: Carve websockets out of rewarder pkg (into vnc_env? - and move this there)
def send_action(self, action_n, env_id):
reactor.callFromThread(self._send_action, env_id, action_n)
return self.pop_errors()
def _send_action(self, env_id, action_n):
with self.lock:
for n, client in zip(action_n, self.clients.values()):
self._send_env_action(client, env_id, action_n[n])
def _send_env_action(self, client, env_id, action_n):
if len(action_n) == 0:
# Hack to skip empty actions. TODO: Find source (throttle?) and fix
return
message = {
'env_id': env_id,
'action': action_n,
}
client.send('v0.agent.action', message, expect_reply=False)
def rewards_count(self):
# TODO: any reason to lock these?
return [client.reward_buffer.count for client in self.clients]
def pop_observation(self):
return [client.reward_buffer.pop_observation() for client in self.clients]
# def _connection_time(self):
# deferreds = []
# for client in self.clients:
# endpoint = client.factory.endpoint
# d = connection_timer.start(endpoint)
# deferreds.append(d)
# d = defer.DeferredList(deferreds, fireOnOneErrback=True, consumeErrors=True)
# return d
# Run this in Twisty therad
class Network(object):
def __init__(self):
self.connection_samples = 10
self.application_ping_samples = 10
self.connection_time_m = None
self.lock = threading.Lock()
self.recalibrate = None
self.client = None
self._ntpdate_reversed_clock_skew = None
self._reversed_clock_skew = None
def active(self):
with self.lock:
return self._reversed_clock_skew is not None
# Used by external consumers
def reversed_clock_skew(self):
with self.lock:
if self._ntpdate_clock_skew is not None:
return self._ntpdate_reversed_clock_skew
else:
return self._reversed_clock_skew
def _report(self):
connection_time = display.display_timestamps(self.connection_time_m)
if self._ntpdate_clock_skew is not None:
ntpdate_clock_skew = display.display_timestamp(self._ntpdate_clock_skew[0])
else:
ntpdate_clock_skew = None
clock_skew = display.display_timestamps_pair(self.clock_skew_m)
application_rtt = display.display_timestamps(self.application_rtt_m)
request_overhead = display.display_timestamps(self.request_overhead_m)
response_overhead = display.display_timestamps(self.response_overhead_m)
extra_logger.info('[%s] Network calibration: ntpdate_clock_skew=%s clock_skew=%s connection_time=%s application_rtt=%s request_overhead=%s response_overhead=%s',
self.client.factory.label, ntpdate_clock_skew, clock_skew, connection_time, application_rtt,
request_overhead, response_overhead)
def _start(self):
def calibrate():
d = defer.Deferred()
def fail(reason):
logger.error('[%s] Could not recalibrate network: %s', self.client.factory.label, reason)
d.addErrback(fail)
self._start_measure_connection_time(d)
self._start()
self.recalibrate = reactor.callLater(5 * 60, calibrate)
def close(self):
if self.recalibrate:
try:
self.recalibrate.cancel()
except twisted.internet.error.AlreadyCalled:
pass
# Called externally
def calibrate(self, client):
d = defer.Deferred()
def success(res):
# If we succeed, kick off the periodic 5 minute
# recalibrations.
self._start()
return res
d.addCallback(success)
self.client = client
# Kinda a hack. Idea is to try using the ntpdate -q offset if
# we can.
skew = self._start_measure_clock_skew()
def succeed(offset):
with self.lock:
self._ntpdate_clock_skew = np.array([offset, offset])
self._ntpdate_reversed_clock_skew = np.array([-offset, -offset])
self._start_measure_connection_time(d)
skew.addCallback(succeed)
def fail(reason):
with self.lock:
self._ntpdate_clock_skew = None
self._ntpdate_reversed_clock_skew = None
extra_logger.info('[%s] Could not determine clock skew with ntpdate; falling back to application-level ping: %s', self.client.factory.label, reason.value)
self._start_measure_connection_time(d)
skew.addErrback(fail)
return d
def _start_measure_connection_time(self, d):
connection_time_m = np.zeros(self.connection_samples)
self._measure_connection_time(d, connection_time_m, 0)
def _measure_connection_time(self, d, connection_time_m, i):
extra_logger.debug('[%s] Measuring connection time (%d/%d)', self.client.factory.label, i+1, len(connection_time_m))
endpoint = self.client.factory.endpoint
timer = connection_timer.start(endpoint)
def success(delta):
connection_time_m[i] = delta
if i+1 < len(connection_time_m):
self._measure_connection_time(d, connection_time_m, i+1)
else:
self.connection_time_m = connection_time_m
self._start_measure_application_ping(d)
def fail(reason):
d.errback(reason)
timer.addCallback(success)
timer.addErrback(fail)
def _start_measure_application_ping(self, d=None):
clock_skew_m = np.zeros((self.application_ping_samples, 2))
request_overhead_m = np.zeros((self.application_ping_samples))
response_overhead_m = np.zeros((self.application_ping_samples))
application_rtt_m = np.zeros((self.application_ping_samples))
self._measure_application_ping(d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, 0)
def _measure_application_ping(self, d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, i):
extra_logger.debug('[%s] Issuing an application-level ping (%d/%d)', self.client.factory.label, i+1, len(clock_skew_m))
start = time.time()
ping = _ping(self.client)
def success(res):
context, request, response = res
end = time.time()
request_sent_at = request['headers']['sent_at'] # local
response_sent_at = response['headers']['sent_at'] # remote
response_received_at = context['start'] # local
# We try to put bounds on clock skew by subtracting
# local and remote times, for local and remote events
# that are causally related.
#
# For example, suppose that the following local/remote
# logical timestamps apply to a request (for a system
# with clock skew of 100):
#
# request_sent local: 0 remote: 100
# request_recieved local: 1 remote: 101
# response_sent local: 2 remote: 102
# response_received local: 3 remote: 103
#
# Then:
#
# # Remote event *after* local is upper bound
# request_recieved.remote - request_sent.local = 101
# # Remote event *before* local is lower bound
# response_sent.remote - response_received.local = 102 - 3 = 99
#
# There's danger of further clock drift over time, but
# we don't need these to be fully accurate, and this
# should be fine for now.
clock_skew_m[i, :] = (response_sent_at-response_received_at, response_sent_at-request_sent_at)
request_overhead_m[i] = request_sent_at - start
response_overhead_m[i] = end - response_received_at
application_rtt_m[i] = response_received_at - request_sent_at
if i+1 < len(clock_skew_m):
self._measure_application_ping(d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, i+1)
else:
self.clock_skew_m = clock_skew_m
self.request_overhead_m = request_overhead_m
self.response_overhead_m = response_overhead_m
self.application_rtt_m = application_rtt_m
self._report()
self._update_exposed_metrics()
# Ok, all done!
if d is not None:
d.callback(self)
ping.addCallback(success)
ping.addErrback(d.errback)
def _update_exposed_metrics(self):
with self.lock:
self._clock_skew = self.clock_skew_m.mean(axis=0) # add to local time to get remote time, as (min, max) values
self._reversed_clock_skew = -self._clock_skew[[1, 0]] # add to remote time to get local time, in format (min, max)
def _start_measure_clock_skew(self):
host = self.client.factory.address.split(':')[0]
return connection_timer.measure_clock_skew(self.client.factory.label, host)
| 42.339147 | 245 | 0.602875 | from autobahn.twisted import websocket
import logging
import numpy as np
import threading
import time
from twisted.python import failure
from twisted.internet import defer, endpoints
import twisted.internet.error
from universe import utils
from universe.twisty import reactor
from universe.rewarder import connection_timer, env_status, reward_buffer, rewarder_client
from universe.utils import display
logger = logging.getLogger(__name__)
extra_logger = logging.getLogger('universe.extra.'+__name__)
def _ping(client):
return client.send('v0.control.ping', {}, expect_reply=True)
class RewarderSession(object):
def __init__(self):
self.lock = threading.RLock()
self.i = 0
self.names_by_id = {}
self.reward_buffers = {}
self.env_statuses = {}
self.errors = {}
self.networks = {}
self.clients = {}
def close(self, name=None, reason=u'closed by RewarderSession.close'):
if name is None:
names = list(self.names_by_id.values())
else:
logger.info('[%s] Closing rewarder connection', name)
names = [name]
self.ids_by_name = {name: id for id, name in self.names_by_id.items()}
for name in names:
with self.lock:
id = self.ids_by_name.pop(name, None)
if id is None:
continue
del self.names_by_id[id]
del self.reward_buffers[id]
del self.env_statuses[id]
self.errors.pop(id, None)
network = self.networks.pop(id)
network.close()
client = self.clients.pop(id, None)
if client is not None:
reactor.callFromThread(client.close, reason=reason)
def connect(self, name, address, label, password, env_id=None, seed=None, fps=60,
start_timeout=None, observer=False, skip_network_calibration=False):
if name in self.reward_buffers:
self.close(name, reason='closing previous connection to reconnect with the same name')
network = Network()
self.names_by_id[self.i] = name
self.reward_buffers[self.i] = reward_buffer.RewardBuffer(label)
self.env_statuses[self.i] = env_status.EnvStatus(label=label, primary=False)
self.networks[self.i] = network
reactor.callFromThread(self._connect,
name=name,
address=address,
env_id=env_id,
seed=seed,
fps=fps,
i=self.i,
network=network,
env_status=self.env_statuses[self.i],
reward_buffer=self.reward_buffers[self.i],
label=label,
start_timeout=start_timeout,
password=password,
observer=observer,
skip_network_calibration=skip_network_calibration,
)
self.i += 1
return network
def _already_closed(self, i):
return i not in self.names_by_id
@defer.inlineCallbacks
def _connect(self, name, address, env_id, seed, fps, i, network, env_status, reward_buffer,
label, password, start_timeout,
observer, skip_network_calibration,
attempt=0, elapsed_sleep_time=0,
):
endpoint = endpoints.clientFromString(reactor, 'tcp:'+address)
factory = websocket.WebSocketClientFactory('ws://'+address)
factory.protocol = rewarder_client.RewarderClient
assert password, "Missing password: {} for rewarder session".format(password)
factory.headers = {'authorization': utils.basic_auth_encode(password), 'openai-observer': 'true' if observer else 'false'}
factory.i = i
factory.endpoint = endpoint
factory.env_status = env_status
factory.reward_buffer = reward_buffer
factory.label = label
factory.address = address
factory.arg_env_id = env_id
factory.arg_fps = fps
def record_error(e):
if isinstance(e, failure.Failure):
e = e.value
with self.lock:
if self._already_closed(factory.i):
extra_logger.info('[%s] Ignoring error for already closed connection: %s', label, e)
elif factory.i not in self.clients:
extra_logger.info('[%s] Received error for connection which has not been fully initialized: %s', label, e)
# We could handle this better, but right now we
# just mark this as a fatal error for the
# backend. Often it actually is.
self.errors[factory.i] = e
else:
extra_logger.info('[%s] Recording fatal error for connection: %s', label, e)
self.errors[factory.i] = e
def retriable_error(e, error_message):
if isinstance(e, failure.Failure):
e = e.value
if self._already_closed(factory.i):
logger.error('[%s] Got error, but giving up on reconnecting, since %d already disconnected', factory.label, factory.i)
return
# Also need to handle DNS errors, so let's just handle everything for now.
if elapsed_sleep_time < start_timeout:
sleep = min((2 * attempt+1), 10)
logger.error('[%s] Waiting on rewarder: %s. Retry in %ds (slept %ds/%ds): %s', factory.label, error_message, sleep, elapsed_sleep_time, start_timeout, e)
reactor.callLater(
sleep, self._connect, name=name, address=address,
env_id=env_id, seed=seed, fps=fps, i=i, network=network,
env_status=env_status, reward_buffer=reward_buffer, label=label,
attempt=attempt+1, elapsed_sleep_time=elapsed_sleep_time+sleep,
start_timeout=start_timeout, password=password,
observer=observer, skip_network_calibration=skip_network_calibration,
)
else:
logger.error('[%s] %s. Retries exceeded (slept %ds/%ds): %s', factory.label, error_message, elapsed_sleep_time, start_timeout, e)
record_error(e)
factory.record_error = record_error
try:
retry_msg = 'establish rewarder TCP connection'
client = yield endpoint.connect(factory)
extra_logger.info('[%s] Rewarder TCP connection established', factory.label)
retry_msg = 'complete WebSocket handshake'
yield client.waitForWebsocketConnection()
extra_logger.info('[%s] Websocket client successfully connected', factory.label)
if not skip_network_calibration:
retry_msg = 'run network calibration'
yield network.calibrate(client)
extra_logger.info('[%s] Network calibration complete', factory.label)
retry_msg = ''
if factory.arg_env_id is not None:
# already receieved an env.describe message
# telling us about a resetting environment, which
# we don't need to bump post.
reply = yield self._send_env_reset(client, seed=seed, episode_id='0')
else:
reply = None
# network. Mark everything as ready to go.
with self.lock:
if factory.i not in self.names_by_id:
# ID has been popped!
logger.info('[%s] Rewarder %d started, but has already been closed', factory.label, factory.i)
client.close(reason='RewarderSession: double-closing, client was closed while RewarderSession was starting')
elif reply is None:
logger.info('[%s] Attached to running environment without reset', factory.label)
else:
context, req, rep = reply
logger.info('[%s] Initial reset complete: episode_id=%s', factory.label, rep['headers']['episode_id'])
self.clients[factory.i] = client
except Exception as e:
if retry_msg:
retriable_error(e, 'failed to ' + retry_msg)
else:
record_error(e)
def pop_errors(self):
errors = {}
with self.lock:
if self.errors:
for i, error in self.errors.items():
name = self.names_by_id[i]
errors[name] = error
self.errors.clear()
return errors
def reset(self, seed=None, env_id=None):
with self.lock:
for i, reward_buffer in self.reward_buffers.items():
reward_buffer.mask()
reactor.callFromThread(self._reset, seed=seed, env_id=env_id)
def _reset(self, seed=None, env_id=None):
with self.lock:
for client in self.clients.values():
d = self._send_env_reset(client, seed=seed, env_id=env_id)
# Total hack to capture the variable in the closure
def callbacks(client):
def success(reply): pass
def fail(reason): client.factory.record_error(reason)
return success, fail
success, fail = callbacks(client)
d.addCallback(success)
d.addErrback(fail)
def _send_env_reset(self, client, seed=None, episode_id=None, env_id=None):
if episode_id is None:
episode_id = client.factory.env_status.episode_id
logger.info('[%s] Sending reset for env_id=%s fps=%s episode_id=%s', client.factory.label, client.factory.arg_env_id, client.factory.arg_fps, episode_id)
return client.send_reset(
env_id=client.factory.arg_env_id if env_id is None else env_id,
seed=seed,
fps=client.factory.arg_fps,
episode_id=episode_id)
def pop(self, warn=True, peek_d=None):
reward_d = {}
done_d = {}
info_d = {}
err_d = self.pop_errors()
for i, reward_buffer in self.reward_buffers.items():
name = self.names_by_id[i]
reward, done, info = reward_buffer.pop(peek_d.get(name))
reward_d[name] = reward
done_d[name] = done
info_d[name] = info
# TODO: use FPS here rather than 60
if warn and any(info.get('stats.reward.count', 0) > 60 for info in info_d.values()):
logger.warn('WARNING: returning more than 60 aggregated rewards: %s. Either your agent is not keeping up with the framerate, or you should have called ".reset()" to clear pending rewards and reset the environments to a known state.',
{name: '{} (episode_id={})'.format(info['stats.reward.count'], info.get('env_status.episode_id')) for name, info in info_d.items()})
return reward_d, done_d, info_d, err_d
def wait(self, timeout=None):
deadline = time.time() + timeout
for client in self.clients:
if timeout is not None:
remaining_timeout = deadline - time.time()
else:
remaining_timeout = None
client.reward_buffer.wait_for_step(timeout=remaining_timeout)
# Hack to test actions over websockets
# TODO: Carve websockets out of rewarder pkg (into vnc_env? - and move this there)
def send_action(self, action_n, env_id):
reactor.callFromThread(self._send_action, env_id, action_n)
return self.pop_errors()
def _send_action(self, env_id, action_n):
with self.lock:
for n, client in zip(action_n, self.clients.values()):
self._send_env_action(client, env_id, action_n[n])
def _send_env_action(self, client, env_id, action_n):
if len(action_n) == 0:
# Hack to skip empty actions. TODO: Find source (throttle?) and fix
return
message = {
'env_id': env_id,
'action': action_n,
}
client.send('v0.agent.action', message, expect_reply=False)
def rewards_count(self):
# TODO: any reason to lock these?
return [client.reward_buffer.count for client in self.clients]
def pop_observation(self):
return [client.reward_buffer.pop_observation() for client in self.clients]
# def _connection_time(self):
# deferreds = []
# for client in self.clients:
# endpoint = client.factory.endpoint
# d = connection_timer.start(endpoint)
# deferreds.append(d)
# d = defer.DeferredList(deferreds, fireOnOneErrback=True, consumeErrors=True)
# return d
# Run this in Twisty therad
class Network(object):
def __init__(self):
self.connection_samples = 10
self.application_ping_samples = 10
self.connection_time_m = None
self.lock = threading.Lock()
self.recalibrate = None
self.client = None
self._ntpdate_reversed_clock_skew = None
self._reversed_clock_skew = None
def active(self):
with self.lock:
return self._reversed_clock_skew is not None
# Used by external consumers
def reversed_clock_skew(self):
with self.lock:
if self._ntpdate_clock_skew is not None:
return self._ntpdate_reversed_clock_skew
else:
return self._reversed_clock_skew
def _report(self):
connection_time = display.display_timestamps(self.connection_time_m)
if self._ntpdate_clock_skew is not None:
ntpdate_clock_skew = display.display_timestamp(self._ntpdate_clock_skew[0])
else:
ntpdate_clock_skew = None
clock_skew = display.display_timestamps_pair(self.clock_skew_m)
application_rtt = display.display_timestamps(self.application_rtt_m)
request_overhead = display.display_timestamps(self.request_overhead_m)
response_overhead = display.display_timestamps(self.response_overhead_m)
extra_logger.info('[%s] Network calibration: ntpdate_clock_skew=%s clock_skew=%s connection_time=%s application_rtt=%s request_overhead=%s response_overhead=%s',
self.client.factory.label, ntpdate_clock_skew, clock_skew, connection_time, application_rtt,
request_overhead, response_overhead)
def _start(self):
def calibrate():
d = defer.Deferred()
def fail(reason):
logger.error('[%s] Could not recalibrate network: %s', self.client.factory.label, reason)
d.addErrback(fail)
self._start_measure_connection_time(d)
self._start()
self.recalibrate = reactor.callLater(5 * 60, calibrate)
def close(self):
if self.recalibrate:
try:
self.recalibrate.cancel()
except twisted.internet.error.AlreadyCalled:
pass
# Called externally
def calibrate(self, client):
d = defer.Deferred()
def success(res):
# If we succeed, kick off the periodic 5 minute
# recalibrations.
self._start()
return res
d.addCallback(success)
self.client = client
# Kinda a hack. Idea is to try using the ntpdate -q offset if
# we can.
skew = self._start_measure_clock_skew()
def succeed(offset):
with self.lock:
self._ntpdate_clock_skew = np.array([offset, offset])
self._ntpdate_reversed_clock_skew = np.array([-offset, -offset])
self._start_measure_connection_time(d)
skew.addCallback(succeed)
def fail(reason):
with self.lock:
self._ntpdate_clock_skew = None
self._ntpdate_reversed_clock_skew = None
extra_logger.info('[%s] Could not determine clock skew with ntpdate; falling back to application-level ping: %s', self.client.factory.label, reason.value)
self._start_measure_connection_time(d)
skew.addErrback(fail)
return d
def _start_measure_connection_time(self, d):
connection_time_m = np.zeros(self.connection_samples)
self._measure_connection_time(d, connection_time_m, 0)
def _measure_connection_time(self, d, connection_time_m, i):
extra_logger.debug('[%s] Measuring connection time (%d/%d)', self.client.factory.label, i+1, len(connection_time_m))
endpoint = self.client.factory.endpoint
timer = connection_timer.start(endpoint)
def success(delta):
connection_time_m[i] = delta
if i+1 < len(connection_time_m):
self._measure_connection_time(d, connection_time_m, i+1)
else:
self.connection_time_m = connection_time_m
self._start_measure_application_ping(d)
def fail(reason):
d.errback(reason)
timer.addCallback(success)
timer.addErrback(fail)
def _start_measure_application_ping(self, d=None):
clock_skew_m = np.zeros((self.application_ping_samples, 2))
request_overhead_m = np.zeros((self.application_ping_samples))
response_overhead_m = np.zeros((self.application_ping_samples))
application_rtt_m = np.zeros((self.application_ping_samples))
self._measure_application_ping(d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, 0)
def _measure_application_ping(self, d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, i):
extra_logger.debug('[%s] Issuing an application-level ping (%d/%d)', self.client.factory.label, i+1, len(clock_skew_m))
start = time.time()
ping = _ping(self.client)
def success(res):
context, request, response = res
end = time.time()
request_sent_at = request['headers']['sent_at'] # local
response_sent_at = response['headers']['sent_at'] # remote
response_received_at = context['start'] # local
# We try to put bounds on clock skew by subtracting
# local and remote times, for local and remote events
# that are causally related.
#
# For example, suppose that the following local/remote
# logical timestamps apply to a request (for a system
# with clock skew of 100):
#
# request_sent local: 0 remote: 100
# request_recieved local: 1 remote: 101
# response_sent local: 2 remote: 102
# response_received local: 3 remote: 103
#
# Then:
#
# # Remote event *after* local is upper bound
# request_recieved.remote - request_sent.local = 101
# # Remote event *before* local is lower bound
# response_sent.remote - response_received.local = 102 - 3 = 99
#
# There's danger of further clock drift over time, but
# should be fine for now.
clock_skew_m[i, :] = (response_sent_at-response_received_at, response_sent_at-request_sent_at)
request_overhead_m[i] = request_sent_at - start
response_overhead_m[i] = end - response_received_at
application_rtt_m[i] = response_received_at - request_sent_at
if i+1 < len(clock_skew_m):
self._measure_application_ping(d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, i+1)
else:
self.clock_skew_m = clock_skew_m
self.request_overhead_m = request_overhead_m
self.response_overhead_m = response_overhead_m
self.application_rtt_m = application_rtt_m
self._report()
self._update_exposed_metrics()
# Ok, all done!
if d is not None:
d.callback(self)
ping.addCallback(success)
ping.addErrback(d.errback)
def _update_exposed_metrics(self):
with self.lock:
self._clock_skew = self.clock_skew_m.mean(axis=0) # add to local time to get remote time, as (min, max) values
self._reversed_clock_skew = -self._clock_skew[[1, 0]] # add to remote time to get local time, in format (min, max)
def _start_measure_clock_skew(self):
host = self.client.factory.address.split(':')[0]
return connection_timer.measure_clock_skew(self.client.factory.label, host)
| true | true |
f72c0d7a15cd90ef41611423f1b1643e68712a61 | 2,372 | py | Python | discord/enums.py | alexyy802/GlowCord | af92f1a11843157aa5484c1781417456175a8ab3 | [
"MIT"
] | null | null | null | discord/enums.py | alexyy802/GlowCord | af92f1a11843157aa5484c1781417456175a8ab3 | [
"MIT"
] | null | null | null | discord/enums.py | alexyy802/GlowCord | af92f1a11843157aa5484c1781417456175a8ab3 | [
"MIT"
] | null | null | null | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Copyright (c) 2021-present tag-epic
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.
--------------
Aliased moodule. See the same file in the glowcord folder for more information
Autogenerated by aliasgen.py
"""
from glowcord.enums import ActivityType, Any, AuditLogAction, AuditLogActionCategory, ButtonStyle, ChannelType, ClassVar, ComponentType, ContentFilter, DefaultAvatar, Dict, Enum, EnumMeta, ExpireBehavior, ExpireBehaviour, InteractionResponseType, InteractionType, InviteTarget, List, MessageType, NSFWLevel, NotificationLevel, Optional, SpeakingState, StagePrivacyLevel, Status, StickerFormatType, StickerType, T, TYPE_CHECKING, TeamMembershipState, Type, TypeVar, UserFlags, VerificationLevel, VideoQualityMode, VoiceRegion, WebhookType, _create_value_cls, _is_descriptor, create_unknown_value, namedtuple, try_enum, types
__all__ = ("Enum", "ChannelType", "MessageType", "VoiceRegion", "SpeakingState", "VerificationLevel", "ContentFilter", "Status", "DefaultAvatar", "AuditLogAction", "AuditLogActionCategory", "UserFlags", "ActivityType", "NotificationLevel", "TeamMembershipState", "WebhookType", "ExpireBehaviour", "ExpireBehavior", "StickerType", "StickerFormatType", "InviteTarget", "VideoQualityMode", "ComponentType", "ButtonStyle", "StagePrivacyLevel", "InteractionType", "InteractionResponseType", "NSFWLevel") | 76.516129 | 623 | 0.802277 |
from glowcord.enums import ActivityType, Any, AuditLogAction, AuditLogActionCategory, ButtonStyle, ChannelType, ClassVar, ComponentType, ContentFilter, DefaultAvatar, Dict, Enum, EnumMeta, ExpireBehavior, ExpireBehaviour, InteractionResponseType, InteractionType, InviteTarget, List, MessageType, NSFWLevel, NotificationLevel, Optional, SpeakingState, StagePrivacyLevel, Status, StickerFormatType, StickerType, T, TYPE_CHECKING, TeamMembershipState, Type, TypeVar, UserFlags, VerificationLevel, VideoQualityMode, VoiceRegion, WebhookType, _create_value_cls, _is_descriptor, create_unknown_value, namedtuple, try_enum, types
__all__ = ("Enum", "ChannelType", "MessageType", "VoiceRegion", "SpeakingState", "VerificationLevel", "ContentFilter", "Status", "DefaultAvatar", "AuditLogAction", "AuditLogActionCategory", "UserFlags", "ActivityType", "NotificationLevel", "TeamMembershipState", "WebhookType", "ExpireBehaviour", "ExpireBehavior", "StickerType", "StickerFormatType", "InviteTarget", "VideoQualityMode", "ComponentType", "ButtonStyle", "StagePrivacyLevel", "InteractionType", "InteractionResponseType", "NSFWLevel") | true | true |
f72c0e67908a76e0ea66de8a4f836e96cdcb736d | 2,393 | py | Python | plugins/hw_wallet/plugin.py | futuro-coin/electrum-futuro | 04910904a6d4d330f202daf0c1975b8296ad8e5d | [
"MIT"
] | 4 | 2019-01-16T14:30:39.000Z | 2021-10-21T04:21:45.000Z | plugins/hw_wallet/plugin.py | futuro-coin/electrum-futuro | 04910904a6d4d330f202daf0c1975b8296ad8e5d | [
"MIT"
] | 1 | 2021-11-15T17:47:31.000Z | 2021-11-15T17:47:31.000Z | plugins/hw_wallet/plugin.py | futuro-coin/electrum-futuro | 04910904a6d4d330f202daf0c1975b8296ad8e5d | [
"MIT"
] | 2 | 2018-12-18T17:32:46.000Z | 2019-01-16T14:30:42.000Z | #!/usr/bin/env python2
# -*- mode: python -*-
#
# Electrum - lightweight Futurocoin client
# Copyright (C) 2016 The Electrum developers
#
# 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.
from electrum.plugins import BasePlugin, hook
from electrum.i18n import _
class HW_PluginBase(BasePlugin):
# Derived classes provide:
#
# class-static variables: client_class, firmware_URL, handler_class,
# libraries_available, libraries_URL, minimum_firmware,
# wallet_class, ckd_public, types, HidTransport
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
self.device = self.keystore_class.device
self.keystore_class.plugin = self
def is_enabled(self):
return True
def device_manager(self):
return self.parent.device_manager
@hook
def close_wallet(self, wallet):
for keystore in wallet.get_keystores():
if isinstance(keystore, self.keystore_class):
self.device_manager().unpair_xpub(keystore.xpub)
def setup_device(self, device_info, wizard, purpose):
"""Called when creating a new wallet or when using the device to decrypt
an existing wallet. Select the device to use. If the device is
uninitialized, go through the initialization process.
"""
raise NotImplementedError()
| 39.229508 | 80 | 0.72921 |
from electrum.plugins import BasePlugin, hook
from electrum.i18n import _
class HW_PluginBase(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
self.device = self.keystore_class.device
self.keystore_class.plugin = self
def is_enabled(self):
return True
def device_manager(self):
return self.parent.device_manager
@hook
def close_wallet(self, wallet):
for keystore in wallet.get_keystores():
if isinstance(keystore, self.keystore_class):
self.device_manager().unpair_xpub(keystore.xpub)
def setup_device(self, device_info, wizard, purpose):
raise NotImplementedError()
| true | true |
f72c0ea16de779f16beca6532d9f0bc2298b0a63 | 214 | py | Python | embiggen/sequences/generic_sequences/__init__.py | monarch-initiative/N2V | 8ae02ca125f1d24ca158c2849f2d9bb1711920b9 | [
"BSD-3-Clause"
] | 2 | 2020-01-30T11:57:37.000Z | 2020-05-02T00:05:49.000Z | embiggen/sequences/generic_sequences/__init__.py | monarch-initiative/N2V | 8ae02ca125f1d24ca158c2849f2d9bb1711920b9 | [
"BSD-3-Clause"
] | 93 | 2020-01-26T00:43:51.000Z | 2020-05-10T03:29:54.000Z | embiggen/sequences/generic_sequences/__init__.py | monarch-initiative/N2V | 8ae02ca125f1d24ca158c2849f2d9bb1711920b9 | [
"BSD-3-Clause"
] | 5 | 2020-02-13T07:18:11.000Z | 2020-03-19T08:03:34.000Z | """Module providing generic sequences that are used throught Embiggen."""
from embiggen.sequences.generic_sequences.edge_prediction_sequence import EdgePredictionSequence
__all__ = [
"EdgePredictionSequence"
] | 35.666667 | 96 | 0.827103 | from embiggen.sequences.generic_sequences.edge_prediction_sequence import EdgePredictionSequence
__all__ = [
"EdgePredictionSequence"
] | true | true |
f72c0f9f033cd93ca71e3dcc3956bdced61ba742 | 11,944 | py | Python | nngp/nngp.py | chrhenning/uncertainty_based_ood | 13c0b9910966544527497497f6ff0441d5334591 | [
"Apache-2.0"
] | null | null | null | nngp/nngp.py | chrhenning/uncertainty_based_ood | 13c0b9910966544527497497f6ff0441d5334591 | [
"Apache-2.0"
] | null | null | null | nngp/nngp.py | chrhenning/uncertainty_based_ood | 13c0b9910966544527497497f6ff0441d5334591 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
# Copyright 2021 Christian Henning
#
# 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.
#
# @title :nngp/nngp.py
# @author :ch
# @contact :henningc@ethz.ch
# @created :04/19/2021
# @version :1.0
# @python_version :3.8.5
r"""
Deep Neural Network as Gaussian Process
---------------------------------------
The module :mod:`nngp.nngp` implements helper functions for Bayesian inference
with Gaussian Processes with a focus on kernels derived from neural network
architectures when taken to the infinite-width limit
(cf. :mod:`nngp.mlp_kernel`).
Specifically, we consider a Gaussian Process
:math:`\mathcal{GP}\big(\mu(x), k(x, x')\big)` with mean function
:math:`\mu(\cdot)` and kernel :math:`k(\cdot, \cdot)`. Unless specified
otherwise, we assume the mean function to be :math:`\mu(x) = 0`. Note, that any
multivariate Gaussian prescribed by the :math:`\mathcal{GP}` at a given set of
input locations is consistent (marginalization from any superset of locations
will always lead to the same distribution) and adheres exchangibility (order of
input locations doesn't affect the distribution except for repositioning the
corresponding function values).
For any given set of inputs :math:`X = x_1, \dots, x_n`, the
:math:`\mathcal{GP}` allows us to specify a prior distribution over function
values :math:`p(f_1, \dots, f_n; x_1, \dots, x_n) \equiv p(F; X)`.
In addition to inputs :math:`x` and function values :math:`f`, we consider
observations :math:`y`, which are obtained via a likelihood function
:math:`p(y \mid f)`.
Using the prior distribution over functions (the :math:`\mathcal{GP}`) and a
dataset :math:`\mathcal{D} = \{(x_n, y_n)\}_{n=1}^N` with inputs :math:`X` and
targets :math:`Y`, one can form a posterior distribution over function values
:math:`f` at an unknown location :math:`x^*` via
.. math::
p(f \mid \mathcal{D}; x^*) = p(f \mid Y; x^* X) = \frac{1}{p(Y; X)} \
\int p(Y \mid F) p(F, f; X, x^*) \, dF
Please see
`Rasmussen and Williams <http://www.gaussianprocess.org/gpml/chapters/RW.pdf>`__
for a broader introduction into Gaussian Processes.
"""
import torch
from warnings import warn
def inference_with_isotropic_gaussian_ll(Y, K_train, K_test, K_all, var=1e-10,
L_mat=None, return_cov=False):
r"""Bayesian inference with Gaussian likelihood and :math:`\mathcal{GP}`
prior.
Here, we consider the case
:math:`p(Y \mid F) = \mathcal{N}(Y; F, \sigma_\epsilon^2 I)`, where the
posterior predictive :math:`p(f \mid \mathcal{D}; x^*)` can be analytically
computed
.. math::
p(f \mid \mathcal{D}; x^*) &= \mathcal{N}(f; \mu^*, \Sigma^*) \\ \
\mu^* &= K(x^*, X) \big( K(X, X) + \sigma_\epsilon^2 I \big)^{-1} Y \\ \
\Sigma^* &= k(x^*, x^*) - K(x^*, X) \big( K(X, X) + \
\sigma_\epsilon^2 I \big)^{-1} K(X, x^*)
Args:
Y (torch.Tensor): The labels :math:`Y` from the training set encoded as
vector of shape ``[m]`` or ``[m, 1]``.
K_train (torch.Tensor): The training data kernel matrix :math:`K(X, X)`.
K_test (torch.Tensor): The test data kernel values :math:`k(x^*, x^*)`.
This is a vector either of shape ``[n]``, where ``n`` is the number
test points, or of shape ``[n, 1]``.
K_all (torch.Tensor): The kernel values between train and test points
:math:`K(x^*, X)`. This is expected to be matrix of shape ``[n,m]``,
where ``m`` is the number of training and ``n`` the number of test
points, or simply a vector of shape ``[m]``, if there is only one
test point.
var (float): The variance :math:`\sigma_\epsilon^2` of the likelihood.
L_mat (torch.Tensor, optional): The matrix :math:`L` resulting from a
Cholesky decomposition of :math:`K(X, X) + \sigma_\epsilon^2 I`.
If provided, the arguments ``K_train`` and ``var`` are ignored.
The function :func:`cholesky_adaptive_noise` may be helpful to
compute ``L_mat``.
return_cov (bool): If ``True``, the return value ``cov`` will be the
full covariance matrix. However, this option requires ``K_test``
to be the full ``[n, n]`` kernel matrix.
Returns:
(tuple): Tuple containing:
- **mean** (torch.Tensor): A tensor of shape ``[n]``, where ``n`` is the
number of test points. The tensor encodes the mean for each test point
of the posterior predictive :math:`\mu^*`.
- **cov** (torch.Tensor): Same as ``mean`` but encoding the variance
:math:`\Sigma^*` of each test point, i.e., the diagonal of the full
covariance matrix.
"""
m = K_train.shape[0] if L_mat is None else L_mat.shape[0]
n = K_test.shape[0]
assert Y.numel() == m
assert K_all.numel() == m*n
if Y.ndim == 1:
Y = Y.view(-1, 1)
if return_cov:
assert K_test.numel() == n*n and K_test.ndim == 2
elif K_test.ndim == 2:
K_test = K_test.view(-1)
if K_all.ndim == 1:
assert n == 1
K_all = K_all.view(n, m)
#inv_K = torch.linalg.inv(K_train + var * torch.eye(m).to(K_train.device))
#mu = torch.matmul(K_all, torch.matmul(inv_K, Y))
#if return_cov:
# sigma = K_test - torch.matmul(K_all, torch.matmul(inv_K, K_all.T))
#else:
# #sigma = K_test - torch.bmm(K_all.view(n, 1, m), torch.matmul(inv_K,
# # K_all.view(n, m, 1))).squeeze()
# sigma = K_test - (K_all * torch.matmul(inv_K,
# K_all.view(n, m, 1)).squeeze(dim=2)).sum(dim=1)
# Note, direct matrix inversion is considered extremely numerically
# unstable. Therefore, Rasmussen et al. propose the use of Cholesky
# decomposition, see Appendix A.4 in
# http://www.gaussianprocess.org/gpml/chapters/RW.pdf
if L_mat is None:
L = torch.linalg.cholesky(K_train + \
var * torch.eye(m).to(K_train.device))
else:
L = L_mat
alpha = torch.triangular_solve(torch.triangular_solve(Y, L, upper=False)[0],
L, upper=False, transpose=True)[0]
mu = torch.matmul(K_all, alpha)
v = torch.triangular_solve(K_all.T, L, upper=False)[0]
if return_cov:
sigma = K_test - torch.matmul(v.T, v)
else:
sigma = K_test - (v * v).sum(dim=0)
if torch.any(sigma < 0):
sigma[sigma < 0] = 1e-5
warn('Some entries of the covariance matrix are negative and set to ' +
'1e-5!')
return mu.squeeze(), sigma
def gen_inference_kernels(X_train, X_test, kernel_func, compute_K_train=True,
full_K_test=False):
r"""Generate the kernel matrices required for inference.
This function generates the kernel matrices / vectors :math:`K(X, X)`,
:math:`K(x^*, X)` and :math:`K(x^*, x^*)`, where :math:`X` are training
inputs and :math:`x^*` are unseen points.
Thus, the function can be seen as helper function for functions like
:func:`inference_with_isotropic_gaussian_ll`.
Args:
X_train (torch.Tensor): A batch of ``m`` training inputs. The tensor
should have shape ``[m, d_in]``, where ``d_in`` is the input
dimensionality. For scalar inputs, one may also pass a tensor of
shape ``[m]``.
X_test (torch.Tensor):A batch of ``n`` unseen test inputs.
kernel_func (func): The kernel function :math:`k(x, x')`. It is expected
to have an interface for a single input ``X`` as described in
the docstring of function:`nngp.mlp_kernel.init_kernel`.
.. code-block:: python
def kernel_func(X):
# Compute kernel values.
return K
compute_K_train (bool): Whether the kernel matrix :math:`K(X, X)`
should be computed. If ``False``, the return value ``K_train`` is
``None``.
full_K_test (bool): Whether the full kernel matrix :math:`K(x^*, x^*)`
of shape ``[n, n]`` should be computed.
Returns:
(tuple): Tuple containing:
- **K_train** (torch.Tensor or None): :math:`K(X, X)`, a tensor of
shape ``[m, m]``.
- **K_test** (torch.Tensor): :math:`K(x^*, x^*)`, a tensor of shape
``[n]``
- **K_all** (torch.Tensor): :math:`K(x^*, X)`, a tensor of shape
``[n,m]``
"""
if compute_K_train:
K_train = kernel_func(X_train)
else:
K_train = None
if full_K_test:
K_test = kernel_func(X_test)
else:
K_test = kernel_func((X_test, X_test))
# Contruct tuples between all train samples and all test samples.
if X_train.ndim == 1: # `d_in == 1`
X_train = X_train.view(-1, 1)
if X_test.ndim == 1:
X_test = X_test.view(-1, 1)
m = X_train.shape[0]
n = X_test.shape[0]
X_all = (X_train.repeat(n, 1),
X_test.view(n, 1, -1).repeat(1, m, 1).view(n*m, -1))
K_all = kernel_func(X_all)
K_all = K_all.view(n, m)
return K_train, K_test, K_all
def cholesky_adaptive_noise(K_train, var=1e-10, var_step=2.):
r"""Cholesky decomposition of a kernel matrix with noise perturbation.
This function computes the Cholesky decomposition of:
.. math::
L L^T = K(X, X) + \sigma_\epsilon^2 I
As kernel matrices :math:`K(X, X)` may easily be (numerically) singular,
tuning the noise :math:`\sigma_\epsilon^2` is crucial. Therefore, this
method will iteratively increase the noise level until the matrix becomes
non-singular.
Args:
(....): See docstring of method :meth:`kernel_efficient`.
var (float or list): The initial variance :math:`\sigma_\epsilon^2`.
If a list of values is provided, then each value in this list is
consecutively tested until a non-singular matrix is constructed.
Note, we assume that the list is sorted from small to large. If none
of the elements in this list will lead to a non-singular matrix, an
exception is raised.
var_step (float): If ``var`` is a single value, then the value specified
here will be iteratively multiplied to increase the variance
:math:`\sigma_\epsilon^2` (therefore ``var_step > 1`` is required).
Returns:
(tuple): Tuple containing:
- **L** (torch.Tensor): The matrix :math:`L` resulting from the
successful Cholesky decomposition.
- **var_chosen** (float): The variance :math:`\sigma_\epsilon^2` that
was chosen to obtain ``L``.
"""
m = K_train.shape[0]
if not isinstance(var, (list, tuple)):
assert var_step > 1.
i = 0
while True:
if isinstance(var, (list, tuple)):
if i >= len(var):
raise RuntimeError('List of variances didn\'t contain high ' +
'enough values.')
curr_var = var[i]
else:
if i == 0:
curr_var = var
else:
curr_var *= var_step
try:
L = torch.linalg.cholesky(K_train + curr_var * torch.eye(m).to( \
K_train.device))
except:
i += 1
continue
return L, curr_var
if __name__ == '__main__':
pass
| 39.681063 | 80 | 0.602646 |
import torch
from warnings import warn
def inference_with_isotropic_gaussian_ll(Y, K_train, K_test, K_all, var=1e-10,
L_mat=None, return_cov=False):
m = K_train.shape[0] if L_mat is None else L_mat.shape[0]
n = K_test.shape[0]
assert Y.numel() == m
assert K_all.numel() == m*n
if Y.ndim == 1:
Y = Y.view(-1, 1)
if return_cov:
assert K_test.numel() == n*n and K_test.ndim == 2
elif K_test.ndim == 2:
K_test = K_test.view(-1)
if K_all.ndim == 1:
assert n == 1
K_all = K_all.view(n, m)
var * torch.eye(m).to(K_train.device))
else:
L = L_mat
alpha = torch.triangular_solve(torch.triangular_solve(Y, L, upper=False)[0],
L, upper=False, transpose=True)[0]
mu = torch.matmul(K_all, alpha)
v = torch.triangular_solve(K_all.T, L, upper=False)[0]
if return_cov:
sigma = K_test - torch.matmul(v.T, v)
else:
sigma = K_test - (v * v).sum(dim=0)
if torch.any(sigma < 0):
sigma[sigma < 0] = 1e-5
warn('Some entries of the covariance matrix are negative and set to ' +
'1e-5!')
return mu.squeeze(), sigma
def gen_inference_kernels(X_train, X_test, kernel_func, compute_K_train=True,
full_K_test=False):
if compute_K_train:
K_train = kernel_func(X_train)
else:
K_train = None
if full_K_test:
K_test = kernel_func(X_test)
else:
K_test = kernel_func((X_test, X_test))
if X_train.ndim == 1:
X_train = X_train.view(-1, 1)
if X_test.ndim == 1:
X_test = X_test.view(-1, 1)
m = X_train.shape[0]
n = X_test.shape[0]
X_all = (X_train.repeat(n, 1),
X_test.view(n, 1, -1).repeat(1, m, 1).view(n*m, -1))
K_all = kernel_func(X_all)
K_all = K_all.view(n, m)
return K_train, K_test, K_all
def cholesky_adaptive_noise(K_train, var=1e-10, var_step=2.):
m = K_train.shape[0]
if not isinstance(var, (list, tuple)):
assert var_step > 1.
i = 0
while True:
if isinstance(var, (list, tuple)):
if i >= len(var):
raise RuntimeError('List of variances didn\'t contain high ' +
'enough values.')
curr_var = var[i]
else:
if i == 0:
curr_var = var
else:
curr_var *= var_step
try:
L = torch.linalg.cholesky(K_train + curr_var * torch.eye(m).to( \
K_train.device))
except:
i += 1
continue
return L, curr_var
if __name__ == '__main__':
pass
| true | true |
f72c0fcbfb5b7caec767f2ca3b4965a9ad74ab72 | 814 | py | Python | python/173.binary-search-tree-iterator.py | fengbaoheng/leetcode | 2b6ec9adea383503acc23622ca5623161f7ca520 | [
"MIT"
] | 1 | 2019-04-11T12:34:55.000Z | 2019-04-11T12:34:55.000Z | python/173.binary-search-tree-iterator.py | fengbaoheng/leetcode | 2b6ec9adea383503acc23622ca5623161f7ca520 | [
"MIT"
] | null | null | null | python/173.binary-search-tree-iterator.py | fengbaoheng/leetcode | 2b6ec9adea383503acc23622ca5623161f7ca520 | [
"MIT"
] | null | null | null | #
# @lc app=leetcode.cn id=173 lang=python3
#
# [173] 二叉搜索树迭代器
#
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
if root is not None:
self.stack.append(root)
# 并不需要一次全部遍历完
# 每次只找到最小的即可
def next(self) -> int:
node = self.stack.pop()
# 没有左子树的节点,即为当前最小的节点
while node.left is not None:
left_node = node.left
node.left = None
self.stack.append(node)
node = left_node
# 缓存该节点的右子树
if node.right is not None:
self.stack.append(node.right)
return node.val
def hasNext(self) -> bool:
return len(self.stack) != 0
| 19.380952 | 41 | 0.545455 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
if root is not None:
self.stack.append(root)
def next(self) -> int:
node = self.stack.pop()
while node.left is not None:
left_node = node.left
node.left = None
self.stack.append(node)
node = left_node
if node.right is not None:
self.stack.append(node.right)
return node.val
def hasNext(self) -> bool:
return len(self.stack) != 0
| true | true |
f72c101791b5714dbca430af69817d1077ddde46 | 307 | py | Python | platform/radio/efr32_multiphy_configurator/pyradioconfig/parts/nixi/targets/Target_IC.py | PascalGuenther/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 82 | 2016-06-29T17:24:43.000Z | 2021-04-16T06:49:17.000Z | platform/radio/efr32_multiphy_configurator/pyradioconfig/parts/nixi/targets/Target_IC.py | PascalGuenther/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 6 | 2022-01-12T18:22:08.000Z | 2022-03-25T10:19:27.000Z | platform/radio/efr32_multiphy_configurator/pyradioconfig/parts/nixi/targets/Target_IC.py | PascalGuenther/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 56 | 2016-08-02T10:50:50.000Z | 2021-07-19T08:57:34.000Z | from pyradioconfig.calculator_model_framework.interfaces.itarget import ITarget
class Target_IC_Nixi(ITarget):
_targetName = ITarget.IC_str
_description = ""
_store_config_output = True
_cfg_location = "nixi"
_tag = ITarget.IC_str
def target_calculate(self, model):
pass
| 21.928571 | 79 | 0.732899 | from pyradioconfig.calculator_model_framework.interfaces.itarget import ITarget
class Target_IC_Nixi(ITarget):
_targetName = ITarget.IC_str
_description = ""
_store_config_output = True
_cfg_location = "nixi"
_tag = ITarget.IC_str
def target_calculate(self, model):
pass
| true | true |
f72c107476fbdd546cdfa11afec00d68c3ac2c51 | 6,189 | py | Python | test/tools/test_tools_jobs.py | Gizmokid2005/sopel | 249a05ab7c6ccb3fb0388e3194514b19897e6990 | [
"EFL-2.0"
] | 555 | 2015-07-25T21:21:43.000Z | 2022-03-28T02:22:38.000Z | test/tools/test_tools_jobs.py | Gizmokid2005/sopel | 249a05ab7c6ccb3fb0388e3194514b19897e6990 | [
"EFL-2.0"
] | 1,177 | 2015-07-31T09:52:31.000Z | 2022-03-26T05:10:34.000Z | test/tools/test_tools_jobs.py | MirahezeBots/sopel | 72aa4fa5bc0bda3cd309ae9c15e86088b29de903 | [
"EFL-2.0"
] | 406 | 2015-07-28T20:34:02.000Z | 2022-03-18T00:37:01.000Z | """Tests for Job Scheduler"""
from __future__ import generator_stop
import time
import pytest
from sopel import loader, plugin
from sopel.tools import jobs
TMP_CONFIG = """
[core]
owner = Bar
nick = Sopel
enable = coretasks
"""
class WithJobMockException(Exception):
pass
@pytest.fixture
def mockconfig(configfactory):
return configfactory('config.cfg', TMP_CONFIG)
def test_jobscheduler_stop(mockconfig, botfactory):
mockbot = botfactory(mockconfig)
scheduler = jobs.Scheduler(mockbot)
assert not scheduler.stopping.is_set(), 'Stopping must not be set at init'
scheduler.stop()
assert scheduler.stopping.is_set(), 'Stopping must have been set'
def test_job_is_ready_to_run():
now = time.time()
job = jobs.Job([5])
assert job.is_ready_to_run(now + 20)
assert not job.is_ready_to_run(now - 20)
def test_job_str():
job = jobs.Job([5])
expected = '<Job (unknown) [5s]>'
assert str(job) == expected
def test_job_str_intervals():
job = jobs.Job([5, 60, 30])
expected = '<Job (unknown) [5s, 30s, 60s]>'
assert str(job) == expected
def test_job_str_handler():
def handler():
pass
job = jobs.Job([5], handler=handler)
expected = '<Job handler [5s]>'
assert str(job) == expected
def test_job_str_handler_plugin():
def handler():
pass
job = jobs.Job([5], plugin='testplugin', handler=handler)
expected = '<Job testplugin.handler [5s]>'
assert str(job) == expected
def test_job_str_label():
def handler():
pass
job = jobs.Job([5], label='testhandler', handler=handler)
expected = '<Job testhandler [5s]>'
assert str(job) == expected
def test_job_str_label_plugin():
def handler():
pass
job = jobs.Job(
[5],
label='testhandler',
plugin='testplugin',
handler=handler,
)
expected = '<Job testplugin.testhandler [5s]>'
assert str(job) == expected
def test_job_str_label_plugin_intervals():
def handler():
pass
job = jobs.Job(
[5, 3600, 60],
label='testhandler',
plugin='testplugin',
handler=handler,
)
expected = '<Job testplugin.testhandler [5s, 60s, 3600s]>'
assert str(job) == expected
def test_job_next():
timestamp = 523549800
job = jobs.Job([5])
job.next_times[5] = timestamp
job.next(timestamp)
assert job.next_times == {
5: timestamp,
}
# assert idempotency
job.next(timestamp)
assert job.next_times == {
5: timestamp,
}
# now the "current time" is in the future compared to the last time
# so the next time should be last time + interval
job.next(timestamp + 1)
assert job.next_times == {
5: timestamp + 5,
}
# let's reset this
job.next_times[5] = timestamp
# now the "current time" is bigger than last time + interval
# so the next time will be the "current time"
job.next(timestamp + 6)
assert job.next_times == {
5: timestamp + 6,
}
def test_job_next_many():
timestamp = 523549800
job = jobs.Job([5, 30])
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
# let's move 6s in the future, so past the 5s and before the 30s
job.next(timestamp + 6)
# the 5s interval => from timestamp + to timestamp + 2 * 5
# the 30s interval => untouched, still in the future
assert job.next_times == {
5: timestamp + 10,
30: timestamp + 30,
}
# assert idempotency
job.next(timestamp + 6)
assert job.next_times == {
5: timestamp + 10,
30: timestamp + 30,
}
# let's reset
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
# now, the next time is bigger than last + 5s,
# but still lower than last + 30s
job.next(timestamp + 15)
assert job.next_times == {
5: timestamp + 15,
30: timestamp + 30,
}
# let's reset again
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
# and now, this time is bigger than both 5s and 30s
job.next(timestamp + 35)
assert job.next_times == {
5: timestamp + 35, # catching up
30: timestamp + 60, # next iteration as intended
}
def test_job_from_callable(mockconfig):
@plugin.interval(5)
@plugin.label('testjob')
def handler(manager):
"""The job's docstring."""
return 'tested'
loader.clean_callable(handler, mockconfig)
handler.plugin_name = 'testplugin'
job = jobs.Job.from_callable(mockconfig, handler)
assert len(job.next_times.items()) == 1
assert 5 in job.next_times
assert job.is_threaded()
assert job.intervals == set([5])
assert job.execute(None) == 'tested'
assert job.get_job_label() == 'testjob'
assert job.get_plugin_name() == 'testplugin'
assert job.get_doc() == "The job's docstring."
assert str(job) == '<Job testplugin.testjob [5s]>'
def test_job_with():
job = jobs.Job([5])
# play with time: move 1s back in the future
last_time = job.next_times[5] = time.time() - 1
assert last_time is not None
with job:
assert job.is_running.is_set()
assert job.next_times[5] == last_time
# now the job is not running anymore, and its next time is last_time + 5s
assert not job.is_running.is_set()
assert job.next_times[5] == last_time + 5
def test_job_with_exception():
job = jobs.Job([5])
# play with time: move 1s back in the future
last_time = job.next_times[5] = time.time() - 1
assert last_time is not None
with pytest.raises(WithJobMockException):
# the "with job" must not prevent the exception from being raised up
with job:
assert job.is_running.is_set()
assert job.next_times[5] == last_time
# fake an exception while the job is running
raise WithJobMockException
# now the job is not running anymore, and its next time is last_time + 5s
# even though an exception was raised!
assert not job.is_running.is_set()
assert job.next_times[5] == last_time + 5
| 23.895753 | 78 | 0.63112 | from __future__ import generator_stop
import time
import pytest
from sopel import loader, plugin
from sopel.tools import jobs
TMP_CONFIG = """
[core]
owner = Bar
nick = Sopel
enable = coretasks
"""
class WithJobMockException(Exception):
pass
@pytest.fixture
def mockconfig(configfactory):
return configfactory('config.cfg', TMP_CONFIG)
def test_jobscheduler_stop(mockconfig, botfactory):
mockbot = botfactory(mockconfig)
scheduler = jobs.Scheduler(mockbot)
assert not scheduler.stopping.is_set(), 'Stopping must not be set at init'
scheduler.stop()
assert scheduler.stopping.is_set(), 'Stopping must have been set'
def test_job_is_ready_to_run():
now = time.time()
job = jobs.Job([5])
assert job.is_ready_to_run(now + 20)
assert not job.is_ready_to_run(now - 20)
def test_job_str():
job = jobs.Job([5])
expected = '<Job (unknown) [5s]>'
assert str(job) == expected
def test_job_str_intervals():
job = jobs.Job([5, 60, 30])
expected = '<Job (unknown) [5s, 30s, 60s]>'
assert str(job) == expected
def test_job_str_handler():
def handler():
pass
job = jobs.Job([5], handler=handler)
expected = '<Job handler [5s]>'
assert str(job) == expected
def test_job_str_handler_plugin():
def handler():
pass
job = jobs.Job([5], plugin='testplugin', handler=handler)
expected = '<Job testplugin.handler [5s]>'
assert str(job) == expected
def test_job_str_label():
def handler():
pass
job = jobs.Job([5], label='testhandler', handler=handler)
expected = '<Job testhandler [5s]>'
assert str(job) == expected
def test_job_str_label_plugin():
def handler():
pass
job = jobs.Job(
[5],
label='testhandler',
plugin='testplugin',
handler=handler,
)
expected = '<Job testplugin.testhandler [5s]>'
assert str(job) == expected
def test_job_str_label_plugin_intervals():
def handler():
pass
job = jobs.Job(
[5, 3600, 60],
label='testhandler',
plugin='testplugin',
handler=handler,
)
expected = '<Job testplugin.testhandler [5s, 60s, 3600s]>'
assert str(job) == expected
def test_job_next():
timestamp = 523549800
job = jobs.Job([5])
job.next_times[5] = timestamp
job.next(timestamp)
assert job.next_times == {
5: timestamp,
}
job.next(timestamp)
assert job.next_times == {
5: timestamp,
}
job.next(timestamp + 1)
assert job.next_times == {
5: timestamp + 5,
}
job.next_times[5] = timestamp
# now the "current time" is bigger than last time + interval
# so the next time will be the "current time"
job.next(timestamp + 6)
assert job.next_times == {
5: timestamp + 6,
}
def test_job_next_many():
timestamp = 523549800
job = jobs.Job([5, 30])
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
# let's move 6s in the future, so past the 5s and before the 30s
job.next(timestamp + 6)
assert job.next_times == {
5: timestamp + 10,
30: timestamp + 30,
}
job.next(timestamp + 6)
assert job.next_times == {
5: timestamp + 10,
30: timestamp + 30,
}
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
# now, the next time is bigger than last + 5s,
# but still lower than last + 30s
job.next(timestamp + 15)
assert job.next_times == {
5: timestamp + 15,
30: timestamp + 30,
}
# let's reset again
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
job.next(timestamp + 35)
assert job.next_times == {
5: timestamp + 35,
30: timestamp + 60,
}
def test_job_from_callable(mockconfig):
@plugin.interval(5)
@plugin.label('testjob')
def handler(manager):
return 'tested'
loader.clean_callable(handler, mockconfig)
handler.plugin_name = 'testplugin'
job = jobs.Job.from_callable(mockconfig, handler)
assert len(job.next_times.items()) == 1
assert 5 in job.next_times
assert job.is_threaded()
assert job.intervals == set([5])
assert job.execute(None) == 'tested'
assert job.get_job_label() == 'testjob'
assert job.get_plugin_name() == 'testplugin'
assert job.get_doc() == "The job's docstring."
assert str(job) == '<Job testplugin.testjob [5s]>'
def test_job_with():
job = jobs.Job([5])
# play with time: move 1s back in the future
last_time = job.next_times[5] = time.time() - 1
assert last_time is not None
with job:
assert job.is_running.is_set()
assert job.next_times[5] == last_time
# now the job is not running anymore, and its next time is last_time + 5s
assert not job.is_running.is_set()
assert job.next_times[5] == last_time + 5
def test_job_with_exception():
job = jobs.Job([5])
# play with time: move 1s back in the future
last_time = job.next_times[5] = time.time() - 1
assert last_time is not None
with pytest.raises(WithJobMockException):
# the "with job" must not prevent the exception from being raised up
with job:
assert job.is_running.is_set()
assert job.next_times[5] == last_time
# fake an exception while the job is running
raise WithJobMockException
# now the job is not running anymore, and its next time is last_time + 5s
# even though an exception was raised!
assert not job.is_running.is_set()
assert job.next_times[5] == last_time + 5
| true | true |
f72c10ad899fc5c2be354213a6c67529edd4ffb0 | 4,949 | py | Python | arco.py | TunkShif/Arco | ae782e77f82b7fd685ede587e659f96a69ec3a87 | [
"MIT"
] | null | null | null | arco.py | TunkShif/Arco | ae782e77f82b7fd685ede587e659f96a69ec3a87 | [
"MIT"
] | null | null | null | arco.py | TunkShif/Arco | ae782e77f82b7fd685ede587e659f96a69ec3a87 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""Arco CLI
Usage:
arco (new | n) -t <title> -g <category> -f <filename>
arco (generate | g)
arco (deploy | d)
arco -h | --help
arco -v | --version
Subcommands:
new Create a new blank page
generate Generate pages
deploy Deployment for github
Options:
-h, --help Help information
-v, --version Show version
-g <tag> Specify the tag
-t <title> Specify the new page title
-f <filename> Specify the new page filename
"""
import os
import json
import markdown
from docopt import docopt
class Utils(object):
def mkdir(self, path):
"Create a folder"
os.mkdir(path)
print(f'INFO: Folder {path} created!')
def read_file(self, file):
"Return the content of a text file"
with open(file, 'r') as f:
return f.read()
def write_file(self, file, content):
"Write text to a file"
path = os.path.split(file)[0] # split file path
if path is not '': # if the folder do not exist, then create it
is_direction = os.path.isdir(path)
if not is_direction:
self.mkdir(path)
with open(file, 'wt') as f:
f.write(content)
print(f"INFO: File {file} modified!")
def gen_html(self, src):
"Return html generated from markdown"
exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite',
'markdown.extensions.tables', 'markdown.extensions.toc',
'markdown.extensions.footnotes']
html = markdown.markdown(src, extensions=exts)
return html
class Arco(object):
def __init__(self, utils):
self.utils = utils
self.config = self.load_config()
def load_config(self):
"Load 'config.json' then return a dict"
raw = self.utils.read_file('config.json')
data = json.loads(raw)
print('INFO: Config loaded!')
return data
def new_page(self, title, tag, file):
"Generate a new markdown page"
text = f"TITLE: {title}\nTAG: {tag}\n"
self.utils.write_file(f'markdown/{file}', text)
def load_md(self, file):
"Return the title and tag of a markdown file"
with open(file, 'r') as f:
lines = f.readlines() # split title and tag
title = lines[0].split("TITLE: ")[1].strip()
tag = lines[1].split("TAG: ")[1].strip()
content = ''.join(lines[2:])
return title, tag, content
def gen_tag_list(self):
"Return a tag list with markdown file and each one's title"
tags = {}
for md in os.listdir('markdown'):
title, tag, _ = self.load_md(f'markdown/{md}')
if tag not in tags.keys():
tags[tag] = []
item = []
item.append(md)
item.append(title)
tags[tag].append(item)
return tags
def gen_page(self):
"Generate html from each markdown file"
root = self.config['root']
year = self.config['year']
author = self.config['author']
url = self.config['url']
if 'blog' not in os.listdir():
self.utils.mkdir('blog')
for md in os.listdir('markdown'):
title, tag, raw_content = self.load_md(f'markdown/{md}')
file_name = md.split('.')[0]
content = self.utils.gen_html(raw_content)
html = utils.read_file('template/page.html')
html = html.format(title, root, root, content, url, year, author)
self.utils.write_file(f'blog/{tag}/{file_name}.html', html)
print(f'INFO: File {file_name}.html generated!')
def gen_index(self):
html = self.utils.read_file('template/index.html')
title = self.config['title']
root = self.config['root']
year = self.config['year']
author = self.config['author']
tags = self.gen_tag_list()
group = []
for tag, pages in tags.items():
group.append('## '+tag)
for page in pages:
link = r"%s%s/%s.html" % (root, tag, page[0].split('.')[0])
item = r"- [%s](%s)" % (page[1], link)
group.append(item)
raw_links = '\n'.join(group)
content = self.utils.gen_html(raw_links)
html = html.format(title, root, title, content, year, author)
self.utils.write_file('blog/index.html', html)
print('INFO: File index.html generated!')
if __name__ == "__main__":
args = docopt(__doc__, version='Arco b0.2')
utils = Utils()
arco = Arco(utils)
if args['new'] or args['n']:
arco.new_page(args['-t'], args['-g'], args['-f'])
if args['generate'] or args['g']:
arco.gen_page()
arco.gen_index()
os.system('cp -r ./template/static/ ./blog/')
| 33.666667 | 78 | 0.555668 |
import os
import json
import markdown
from docopt import docopt
class Utils(object):
def mkdir(self, path):
os.mkdir(path)
print(f'INFO: Folder {path} created!')
def read_file(self, file):
with open(file, 'r') as f:
return f.read()
def write_file(self, file, content):
path = os.path.split(file)[0]
if path is not '':
is_direction = os.path.isdir(path)
if not is_direction:
self.mkdir(path)
with open(file, 'wt') as f:
f.write(content)
print(f"INFO: File {file} modified!")
def gen_html(self, src):
exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite',
'markdown.extensions.tables', 'markdown.extensions.toc',
'markdown.extensions.footnotes']
html = markdown.markdown(src, extensions=exts)
return html
class Arco(object):
def __init__(self, utils):
self.utils = utils
self.config = self.load_config()
def load_config(self):
raw = self.utils.read_file('config.json')
data = json.loads(raw)
print('INFO: Config loaded!')
return data
def new_page(self, title, tag, file):
text = f"TITLE: {title}\nTAG: {tag}\n"
self.utils.write_file(f'markdown/{file}', text)
def load_md(self, file):
with open(file, 'r') as f:
lines = f.readlines()
title = lines[0].split("TITLE: ")[1].strip()
tag = lines[1].split("TAG: ")[1].strip()
content = ''.join(lines[2:])
return title, tag, content
def gen_tag_list(self):
tags = {}
for md in os.listdir('markdown'):
title, tag, _ = self.load_md(f'markdown/{md}')
if tag not in tags.keys():
tags[tag] = []
item = []
item.append(md)
item.append(title)
tags[tag].append(item)
return tags
def gen_page(self):
root = self.config['root']
year = self.config['year']
author = self.config['author']
url = self.config['url']
if 'blog' not in os.listdir():
self.utils.mkdir('blog')
for md in os.listdir('markdown'):
title, tag, raw_content = self.load_md(f'markdown/{md}')
file_name = md.split('.')[0]
content = self.utils.gen_html(raw_content)
html = utils.read_file('template/page.html')
html = html.format(title, root, root, content, url, year, author)
self.utils.write_file(f'blog/{tag}/{file_name}.html', html)
print(f'INFO: File {file_name}.html generated!')
def gen_index(self):
html = self.utils.read_file('template/index.html')
title = self.config['title']
root = self.config['root']
year = self.config['year']
author = self.config['author']
tags = self.gen_tag_list()
group = []
for tag, pages in tags.items():
group.append('## '+tag)
for page in pages:
link = r"%s%s/%s.html" % (root, tag, page[0].split('.')[0])
item = r"- [%s](%s)" % (page[1], link)
group.append(item)
raw_links = '\n'.join(group)
content = self.utils.gen_html(raw_links)
html = html.format(title, root, title, content, year, author)
self.utils.write_file('blog/index.html', html)
print('INFO: File index.html generated!')
if __name__ == "__main__":
args = docopt(__doc__, version='Arco b0.2')
utils = Utils()
arco = Arco(utils)
if args['new'] or args['n']:
arco.new_page(args['-t'], args['-g'], args['-f'])
if args['generate'] or args['g']:
arco.gen_page()
arco.gen_index()
os.system('cp -r ./template/static/ ./blog/')
| true | true |
f72c11ddf5cf9792898f16eb88c27c05d0a7fa22 | 121 | py | Python | modules/utility/exit_failure.py | naskya/testcase-generator | 02765184a275152e1d8c177f2028ca8db315cfee | [
"MIT"
] | 4 | 2020-09-23T07:11:41.000Z | 2022-02-02T09:08:21.000Z | modules/utility/exit_failure.py | naskya/testcase-generator | 02765184a275152e1d8c177f2028ca8db315cfee | [
"MIT"
] | 5 | 2021-08-29T18:23:01.000Z | 2021-11-20T03:53:19.000Z | modules/utility/exit_failure.py | naskya/testcase-generator | 02765184a275152e1d8c177f2028ca8db315cfee | [
"MIT"
] | null | null | null | import sys
import typing
import colorama
def exit_failure() -> typing.NoReturn:
colorama.deinit()
sys.exit(1)
| 12.1 | 38 | 0.710744 | import sys
import typing
import colorama
def exit_failure() -> typing.NoReturn:
colorama.deinit()
sys.exit(1)
| true | true |
f72c12cb5d888c460ea2425493c4ccae0a17c163 | 2,097 | py | Python | third_party/catapult/dashboard/dashboard/pinpoint/models/quest/run_telemetry_test.py | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/catapult/dashboard/dashboard/pinpoint/models/quest/run_telemetry_test.py | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/catapult/dashboard/dashboard/pinpoint/models/quest/run_telemetry_test.py | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | # Copyright 2018 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.
"""Quest for running a Telemetry benchmark in Swarming."""
import copy
from dashboard.pinpoint.models.quest import run_test
_DEFAULT_EXTRA_ARGS = [
'-v', '--upload-results', '--output-format', 'histograms']
class RunTelemetryTest(run_test.RunTest):
def Start(self, change, isolate_server, isolate_hash):
# For results2 to differentiate between runs, we need to add the
# Telemetry parameter `--results-label <change>` to the runs.
extra_args = copy.copy(self._extra_args)
extra_args += ('--results-label', str(change))
return self._Start(change, isolate_server, isolate_hash, extra_args)
@classmethod
def FromDict(cls, arguments):
swarming_extra_args = []
benchmark = arguments.get('benchmark')
if not benchmark:
raise TypeError('Missing "benchmark" argument.')
if arguments.get('target') == 'performance_test_suite':
swarming_extra_args += ('--benchmarks', benchmark)
else:
# TODO: Remove this hack when all builders build performance_test_suite.
swarming_extra_args.append(benchmark)
story = arguments.get('story')
if story:
swarming_extra_args += ('--story-filter', story)
# TODO: Workaround for crbug.com/677843.
if (benchmark.startswith('startup.warm') or
benchmark.startswith('start_with_url.warm')):
swarming_extra_args += ('--pageset-repeat', '2')
else:
swarming_extra_args += ('--pageset-repeat', '1')
browser = arguments.get('browser')
if not browser:
raise TypeError('Missing "browser" argument.')
swarming_extra_args += ('--browser', browser)
if browser == 'android-webview':
# TODO: Share code with the perf waterfall configs. crbug.com/771680
swarming_extra_args += ('--webview-embedder-apk',
'../../out/Release/apks/SystemWebViewShell.apk')
return cls._FromDict(arguments, swarming_extra_args + _DEFAULT_EXTRA_ARGS)
| 34.377049 | 78 | 0.69051 |
import copy
from dashboard.pinpoint.models.quest import run_test
_DEFAULT_EXTRA_ARGS = [
'-v', '--upload-results', '--output-format', 'histograms']
class RunTelemetryTest(run_test.RunTest):
def Start(self, change, isolate_server, isolate_hash):
extra_args = copy.copy(self._extra_args)
extra_args += ('--results-label', str(change))
return self._Start(change, isolate_server, isolate_hash, extra_args)
@classmethod
def FromDict(cls, arguments):
swarming_extra_args = []
benchmark = arguments.get('benchmark')
if not benchmark:
raise TypeError('Missing "benchmark" argument.')
if arguments.get('target') == 'performance_test_suite':
swarming_extra_args += ('--benchmarks', benchmark)
else:
swarming_extra_args.append(benchmark)
story = arguments.get('story')
if story:
swarming_extra_args += ('--story-filter', story)
if (benchmark.startswith('startup.warm') or
benchmark.startswith('start_with_url.warm')):
swarming_extra_args += ('--pageset-repeat', '2')
else:
swarming_extra_args += ('--pageset-repeat', '1')
browser = arguments.get('browser')
if not browser:
raise TypeError('Missing "browser" argument.')
swarming_extra_args += ('--browser', browser)
if browser == 'android-webview':
swarming_extra_args += ('--webview-embedder-apk',
'../../out/Release/apks/SystemWebViewShell.apk')
return cls._FromDict(arguments, swarming_extra_args + _DEFAULT_EXTRA_ARGS)
| true | true |
f72c12d312063efabbecedfddb86898a11b4cc57 | 750 | py | Python | sdk/python/pulumi_aws_native/networkmanager/__init__.py | pulumi/pulumi-aws-native | 1ae4a4d9c2256b2a79ca536f8d8497b28d10e4c3 | [
"Apache-2.0"
] | 29 | 2021-09-30T19:32:07.000Z | 2022-03-22T21:06:08.000Z | sdk/python/pulumi_aws_native/networkmanager/__init__.py | pulumi/pulumi-aws-native | 1ae4a4d9c2256b2a79ca536f8d8497b28d10e4c3 | [
"Apache-2.0"
] | 232 | 2021-09-30T19:26:26.000Z | 2022-03-31T23:22:06.000Z | sdk/python/pulumi_aws_native/networkmanager/__init__.py | pulumi/pulumi-aws-native | 1ae4a4d9c2256b2a79ca536f8d8497b28d10e4c3 | [
"Apache-2.0"
] | 4 | 2021-11-10T19:42:01.000Z | 2022-02-05T10:15:49.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from .customer_gateway_association import *
from .device import *
from .get_customer_gateway_association import *
from .get_device import *
from .get_global_network import *
from .get_link import *
from .get_link_association import *
from .get_site import *
from .get_transit_gateway_registration import *
from .global_network import *
from .link import *
from .link_association import *
from .site import *
from .transit_gateway_registration import *
from ._inputs import *
from . import outputs
| 31.25 | 80 | 0.777333 |
from .. import _utilities
import typing
# Export this package's modules as members:
from .customer_gateway_association import *
from .device import *
from .get_customer_gateway_association import *
from .get_device import *
from .get_global_network import *
from .get_link import *
from .get_link_association import *
from .get_site import *
from .get_transit_gateway_registration import *
from .global_network import *
from .link import *
from .link_association import *
from .site import *
from .transit_gateway_registration import *
from ._inputs import *
from . import outputs
| true | true |
f72c136f7e297c4a25e30f41fa955aa92ac206dd | 28,541 | py | Python | python/ray/autoscaler/_private/command_runner.py | chinganc/ray | f91c4555270cbcb86adc6c41a9074e2f69721aad | [
"Apache-2.0"
] | null | null | null | python/ray/autoscaler/_private/command_runner.py | chinganc/ray | f91c4555270cbcb86adc6c41a9074e2f69721aad | [
"Apache-2.0"
] | null | null | null | python/ray/autoscaler/_private/command_runner.py | chinganc/ray | f91c4555270cbcb86adc6c41a9074e2f69721aad | [
"Apache-2.0"
] | null | null | null | from getpass import getuser
from shlex import quote
from typing import Dict
import click
import hashlib
import json
import logging
import os
import subprocess
import sys
import time
import warnings
from ray.autoscaler.command_runner import CommandRunnerInterface
from ray.autoscaler._private.docker import check_bind_mounts_cmd, \
check_docker_running_cmd, \
check_docker_image, \
docker_start_cmds, \
DOCKER_MOUNT_PREFIX, \
with_docker_exec
from ray.autoscaler._private.log_timer import LogTimer
from ray.autoscaler._private.subprocess_output_util import (
run_cmd_redirected, ProcessRunnerError, is_output_redirected)
from ray.autoscaler._private.cli_logger import cli_logger
import colorful as cf
logger = logging.getLogger(__name__)
# How long to wait for a node to start, in seconds
NODE_START_WAIT_S = 300
HASH_MAX_LENGTH = 10
KUBECTL_RSYNC = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "kubernetes/kubectl-rsync.sh")
_config = {"use_login_shells": True, "silent_rsync": True}
def is_rsync_silent():
return _config["silent_rsync"]
def set_rsync_silent(val):
"""Choose whether to silence rsync output.
Most commands will want to list rsync'd files themselves rather than
print the default rsync spew.
"""
_config["silent_rsync"] = val
def is_using_login_shells():
return _config["use_login_shells"]
def set_using_login_shells(val):
"""Choose between login and non-interactive shells.
Non-interactive shells have the benefit of receiving less output from
subcommands (since progress bars and TTY control codes are not printed).
Sometimes this can be significant since e.g. `pip install` prints
hundreds of progress bar lines when downloading.
Login shells have the benefit of working very close to how a proper bash
session does, regarding how scripts execute and how the environment is
setup. This is also how all commands were ran in the past. The only reason
to use login shells over non-interactive shells is if you need some weird
and non-robust tool to work.
Args:
val (bool): If true, login shells will be used to run all commands.
"""
_config["use_login_shells"] = val
def _with_environment_variables(cmd: str,
environment_variables: Dict[str, object]):
"""Prepend environment variables to a shell command.
Args:
cmd (str): The base command.
environment_variables (Dict[str, object]): The set of environment
variables. If an environment variable value is a dict, it will
automatically be converted to a one line yaml string.
"""
as_strings = []
for key, val in environment_variables.items():
val = json.dumps(val, separators=(",", ":"))
s = "export {}={};".format(key, quote(val))
as_strings.append(s)
all_vars = "".join(as_strings)
return all_vars + cmd
def _with_interactive(cmd):
force_interactive = (
f"true && source ~/.bashrc && "
f"export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && ({cmd})")
return ["bash", "--login", "-c", "-i", quote(force_interactive)]
class KubernetesCommandRunner(CommandRunnerInterface):
def __init__(self, log_prefix, namespace, node_id, auth_config,
process_runner):
self.log_prefix = log_prefix
self.process_runner = process_runner
self.node_id = str(node_id)
self.namespace = namespace
self.kubectl = ["kubectl", "-n", self.namespace]
def run(
self,
cmd=None,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto", # Unused argument.
ssh_options_override_ssh_key="", # Unused argument.
shutdown_after_run=False,
):
if shutdown_after_run:
cmd += "; sudo shutdown -h now"
if cmd and port_forward:
raise Exception(
"exec with Kubernetes can't forward ports and execute"
"commands together.")
if port_forward:
if not isinstance(port_forward, list):
port_forward = [port_forward]
port_forward_cmd = self.kubectl + [
"port-forward",
self.node_id,
] + [
"{}:{}".format(local, remote) for local, remote in port_forward
]
logger.info("Port forwarding with: {}".format(
" ".join(port_forward_cmd)))
port_forward_process = subprocess.Popen(port_forward_cmd)
port_forward_process.wait()
# We should never get here, this indicates that port forwarding
# failed, likely because we couldn't bind to a port.
pout, perr = port_forward_process.communicate()
exception_str = " ".join(
port_forward_cmd) + " failed with error: " + perr
raise Exception(exception_str)
else:
final_cmd = self.kubectl + ["exec", "-it"]
final_cmd += [
self.node_id,
"--",
]
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
cmd = _with_interactive(cmd)
cmd_prefix = " ".join(final_cmd)
final_cmd += cmd
# `kubectl exec` + subprocess w/ list of args has unexpected
# side-effects.
final_cmd = " ".join(final_cmd)
logger.info(self.log_prefix + "Running {}".format(final_cmd))
try:
if with_output:
return self.process_runner.check_output(
final_cmd, shell=True)
else:
self.process_runner.check_call(final_cmd, shell=True)
except subprocess.CalledProcessError:
if exit_on_fail:
quoted_cmd = cmd_prefix + quote(" ".join(cmd))
logger.error(
self.log_prefix +
"Command failed: \n\n {}\n".format(quoted_cmd))
sys.exit(1)
else:
raise
def run_rsync_up(self, source, target, options=None):
if target.startswith("~"):
target = "/root" + target[1:]
try:
self.process_runner.check_call([
KUBECTL_RSYNC,
"-avz",
source,
"{}@{}:{}".format(self.node_id, self.namespace, target),
])
except Exception as e:
warnings.warn(
self.log_prefix +
"rsync failed: '{}'. Falling back to 'kubectl cp'".format(e),
UserWarning)
if target.startswith("~"):
target = "/root" + target[1:]
self.process_runner.check_call(self.kubectl + [
"cp", source, "{}/{}:{}".format(self.namespace, self.node_id,
target)
])
def run_rsync_down(self, source, target, options=None):
if target.startswith("~"):
target = "/root" + target[1:]
try:
self.process_runner.check_call([
KUBECTL_RSYNC,
"-avz",
"{}@{}:{}".format(self.node_id, self.namespace, source),
target,
])
except Exception as e:
warnings.warn(
self.log_prefix +
"rsync failed: '{}'. Falling back to 'kubectl cp'".format(e),
UserWarning)
if target.startswith("~"):
target = "/root" + target[1:]
self.process_runner.check_call(self.kubectl + [
"cp", "{}/{}:{}".format(self.namespace, self.node_id, source),
target
])
def remote_shell_command_str(self):
return "{} exec -it {} bash".format(" ".join(self.kubectl),
self.node_id)
class SSHOptions:
def __init__(self, ssh_key, control_path=None, **kwargs):
self.ssh_key = ssh_key
self.arg_dict = {
# Supresses initial fingerprint verification.
"StrictHostKeyChecking": "no",
# SSH IP and fingerprint pairs no longer added to known_hosts.
# This is to remove a "REMOTE HOST IDENTIFICATION HAS CHANGED"
# warning if a new node has the same IP as a previously
# deleted node, because the fingerprints will not match in
# that case.
"UserKnownHostsFile": os.devnull,
# Try fewer extraneous key pairs.
"IdentitiesOnly": "yes",
# Abort if port forwarding fails (instead of just printing to
# stderr).
"ExitOnForwardFailure": "yes",
# Quickly kill the connection if network connection breaks (as
# opposed to hanging/blocking).
"ServerAliveInterval": 5,
"ServerAliveCountMax": 3
}
if control_path:
self.arg_dict.update({
"ControlMaster": "auto",
"ControlPath": "{}/%C".format(control_path),
"ControlPersist": "10s",
})
self.arg_dict.update(kwargs)
def to_ssh_options_list(self, *, timeout=60):
self.arg_dict["ConnectTimeout"] = "{}s".format(timeout)
ssh_key_option = ["-i", self.ssh_key] if self.ssh_key else []
return ssh_key_option + [
x for y in (["-o", "{}={}".format(k, v)]
for k, v in self.arg_dict.items()
if v is not None) for x in y
]
class SSHCommandRunner(CommandRunnerInterface):
def __init__(self, log_prefix, node_id, provider, auth_config,
cluster_name, process_runner, use_internal_ip):
ssh_control_hash = hashlib.md5(cluster_name.encode()).hexdigest()
ssh_user_hash = hashlib.md5(getuser().encode()).hexdigest()
ssh_control_path = "/tmp/ray_ssh_{}/{}".format(
ssh_user_hash[:HASH_MAX_LENGTH],
ssh_control_hash[:HASH_MAX_LENGTH])
self.log_prefix = log_prefix
self.process_runner = process_runner
self.node_id = node_id
self.use_internal_ip = use_internal_ip
self.provider = provider
self.ssh_private_key = auth_config.get("ssh_private_key")
self.ssh_user = auth_config["ssh_user"]
self.ssh_control_path = ssh_control_path
self.ssh_ip = None
self.ssh_proxy_command = auth_config.get("ssh_proxy_command", None)
self.ssh_options = SSHOptions(
self.ssh_private_key,
self.ssh_control_path,
ProxyCommand=self.ssh_proxy_command)
def _get_node_ip(self):
if self.use_internal_ip:
return self.provider.internal_ip(self.node_id)
else:
return self.provider.external_ip(self.node_id)
def _wait_for_ip(self, deadline):
# if we have IP do not print waiting info
ip = self._get_node_ip()
if ip is not None:
cli_logger.labeled_value("Fetched IP", ip)
return ip
interval = 10
with cli_logger.timed("Waiting for IP"):
while time.time() < deadline and \
not self.provider.is_terminated(self.node_id):
cli_logger.old_info(logger, "{}Waiting for IP...",
self.log_prefix)
ip = self._get_node_ip()
if ip is not None:
cli_logger.labeled_value("Received", ip)
return ip
cli_logger.print("Not yet available, retrying in {} seconds",
cf.bold(str(interval)))
time.sleep(interval)
return None
def _set_ssh_ip_if_required(self):
if self.ssh_ip is not None:
return
# We assume that this never changes.
# I think that's reasonable.
deadline = time.time() + NODE_START_WAIT_S
with LogTimer(self.log_prefix + "Got IP"):
ip = self._wait_for_ip(deadline)
cli_logger.doassert(ip is not None,
"Could not get node IP.") # todo: msg
assert ip is not None, "Unable to find IP of node"
self.ssh_ip = ip
# This should run before any SSH commands and therefore ensure that
# the ControlPath directory exists, allowing SSH to maintain
# persistent sessions later on.
try:
os.makedirs(self.ssh_control_path, mode=0o700, exist_ok=True)
except OSError as e:
cli_logger.warning("{}", str(e)) # todo: msg
cli_logger.old_warning(logger, "{}", str(e))
def _run_helper(self,
final_cmd,
with_output=False,
exit_on_fail=False,
silent=False):
"""Run a command that was already setup with SSH and `bash` settings.
Args:
cmd (List[str]):
Full command to run. Should include SSH options and other
processing that we do.
with_output (bool):
If `with_output` is `True`, command stdout and stderr
will be captured and returned.
exit_on_fail (bool):
If `exit_on_fail` is `True`, the process will exit
if the command fails (exits with a code other than 0).
Raises:
ProcessRunnerError if using new log style and disabled
login shells.
click.ClickException if using login shells.
"""
try:
# For now, if the output is needed we just skip the new logic.
# In the future we could update the new logic to support
# capturing output, but it is probably not needed.
if not cli_logger.old_style and not with_output:
return run_cmd_redirected(
final_cmd,
process_runner=self.process_runner,
silent=silent,
use_login_shells=is_using_login_shells())
if with_output:
return self.process_runner.check_output(final_cmd)
else:
return self.process_runner.check_call(final_cmd)
except subprocess.CalledProcessError as e:
quoted_cmd = " ".join(final_cmd[:-1] + [quote(final_cmd[-1])])
if not cli_logger.old_style and not is_using_login_shells():
raise ProcessRunnerError(
"Command failed",
"ssh_command_failed",
code=e.returncode,
command=quoted_cmd)
if exit_on_fail:
raise click.ClickException(
"Command failed:\n\n {}\n".format(quoted_cmd)) from None
else:
fail_msg = "SSH command failed."
if is_output_redirected():
fail_msg += " See above for the output from the failure."
raise click.ClickException(fail_msg) from None
def run(
self,
cmd,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto", # Unused argument.
ssh_options_override_ssh_key="",
shutdown_after_run=False,
):
if shutdown_after_run:
cmd += "; sudo shutdown -h now"
if ssh_options_override_ssh_key:
ssh_options = SSHOptions(ssh_options_override_ssh_key)
else:
ssh_options = self.ssh_options
assert isinstance(
ssh_options, SSHOptions
), "ssh_options must be of type SSHOptions, got {}".format(
type(ssh_options))
self._set_ssh_ip_if_required()
if is_using_login_shells():
ssh = ["ssh", "-tt"]
else:
ssh = ["ssh"]
if port_forward:
with cli_logger.group("Forwarding ports"):
if not isinstance(port_forward, list):
port_forward = [port_forward]
for local, remote in port_forward:
cli_logger.verbose(
"Forwarding port {} to port {} on localhost.",
cf.bold(local), cf.bold(remote)) # todo: msg
cli_logger.old_info(logger,
"{}Forwarding {} -> localhost:{}",
self.log_prefix, local, remote)
ssh += ["-L", "{}:localhost:{}".format(remote, local)]
final_cmd = ssh + ssh_options.to_ssh_options_list(timeout=timeout) + [
"{}@{}".format(self.ssh_user, self.ssh_ip)
]
if cmd:
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
if is_using_login_shells():
final_cmd += _with_interactive(cmd)
else:
final_cmd += [cmd]
cli_logger.old_info(logger, "{}Running {}", self.log_prefix,
" ".join(final_cmd))
else:
# We do this because `-o ControlMaster` causes the `-N` flag to
# still create an interactive shell in some ssh versions.
final_cmd.append("while true; do sleep 86400; done")
cli_logger.verbose("Running `{}`", cf.bold(cmd))
with cli_logger.indented():
cli_logger.very_verbose("Full command is `{}`",
cf.bold(" ".join(final_cmd)))
if cli_logger.verbosity > 0:
with cli_logger.indented():
return self._run_helper(final_cmd, with_output, exit_on_fail)
else:
return self._run_helper(final_cmd, with_output, exit_on_fail)
def run_rsync_up(self, source, target, options=None):
self._set_ssh_ip_if_required()
command = [
"rsync", "--rsh",
subprocess.list2cmdline(
["ssh"] + self.ssh_options.to_ssh_options_list(timeout=120)),
"-avz", source, "{}@{}:{}".format(self.ssh_user, self.ssh_ip,
target)
]
cli_logger.verbose("Running `{}`", cf.bold(" ".join(command)))
self._run_helper(command, silent=is_rsync_silent())
def run_rsync_down(self, source, target, options=None):
self._set_ssh_ip_if_required()
command = [
"rsync", "--rsh",
subprocess.list2cmdline(
["ssh"] + self.ssh_options.to_ssh_options_list(timeout=120)),
"-avz", "{}@{}:{}".format(self.ssh_user, self.ssh_ip,
source), target
]
cli_logger.verbose("Running `{}`", cf.bold(" ".join(command)))
self._run_helper(command, silent=is_rsync_silent())
def remote_shell_command_str(self):
if self.ssh_private_key:
return "ssh -o IdentitiesOnly=yes -i {} {}@{}\n".format(
self.ssh_private_key, self.ssh_user, self.ssh_ip)
else:
return "ssh -o IdentitiesOnly=yes {}@{}\n".format(
self.ssh_user, self.ssh_ip)
class DockerCommandRunner(CommandRunnerInterface):
def __init__(self, docker_config, **common_args):
self.ssh_command_runner = SSHCommandRunner(**common_args)
self.container_name = docker_config["container_name"]
self.docker_config = docker_config
self.home_dir = None
self.initialized = False
def run(
self,
cmd,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto",
ssh_options_override_ssh_key="",
shutdown_after_run=False,
):
if run_env == "auto":
run_env = "host" if cmd.find("docker") == 0 else "docker"
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
if run_env == "docker":
cmd = self._docker_expand_user(cmd, any_char=True)
cmd = " ".join(_with_interactive(cmd))
cmd = with_docker_exec(
[cmd],
container_name=self.container_name,
with_interactive=True)[0]
if shutdown_after_run:
# sudo shutdown should run after `with_docker_exec` command above
cmd += "; sudo shutdown -h now"
# Do not pass shutdown_after_run argument to ssh_command_runner.run()
# since it is handled above.
return self.ssh_command_runner.run(
cmd,
timeout=timeout,
exit_on_fail=exit_on_fail,
port_forward=port_forward,
with_output=with_output,
ssh_options_override_ssh_key=ssh_options_override_ssh_key)
def run_rsync_up(self, source, target, options=None):
options = options or {}
host_destination = os.path.join(DOCKER_MOUNT_PREFIX,
target.lstrip("/"))
self.ssh_command_runner.run(
f"mkdir -p {os.path.dirname(host_destination.rstrip('/'))}")
self.ssh_command_runner.run_rsync_up(
source, host_destination, options=None)
if self._check_container_status() and not options.get(
"file_mount", False):
if os.path.isdir(source):
# Adding a "." means that docker copies the *contents*
# Without it, docker copies the source *into* the target
host_destination += "/."
self.ssh_command_runner.run("docker cp {} {}:{}".format(
host_destination, self.container_name,
self._docker_expand_user(target)))
def run_rsync_down(self, source, target, options=None):
options = options or {}
host_source = os.path.join(DOCKER_MOUNT_PREFIX, source.lstrip("/"))
self.ssh_command_runner.run(
f"mkdir -p {os.path.dirname(host_source.rstrip('/'))}")
if source[-1] == "/":
source += "."
# Adding a "." means that docker copies the *contents*
# Without it, docker copies the source *into* the target
if not options.get("file_mount", False):
self.ssh_command_runner.run("docker cp {}:{} {}".format(
self.container_name, self._docker_expand_user(source),
host_source))
self.ssh_command_runner.run_rsync_down(
host_source, target, options=None)
def remote_shell_command_str(self):
inner_str = self.ssh_command_runner.remote_shell_command_str().replace(
"ssh", "ssh -tt", 1).strip("\n")
return inner_str + " docker exec -it {} /bin/bash\n".format(
self.container_name)
def _check_docker_installed(self):
no_exist = "NoExist"
output = self.ssh_command_runner.run(
f"command -v docker || echo '{no_exist}'", with_output=True)
cleaned_output = output.decode().strip()
if no_exist in cleaned_output or "docker" not in cleaned_output:
install_commands = [
"curl -fsSL https://get.docker.com -o get-docker.sh",
"sudo sh get-docker.sh", "sudo usermod -aG docker $USER",
"sudo systemctl restart docker -f"
]
logger.error(
"Docker not installed. You can install Docker by adding the "
"following commands to 'initialization_commands':\n" +
"\n".join(install_commands))
def _check_container_status(self):
if self.initialized:
return True
output = self.ssh_command_runner.run(
check_docker_running_cmd(self.container_name),
with_output=True).decode("utf-8").strip()
# Checks for the false positive where "true" is in the container name
return ("true" in output.lower()
and "no such object" not in output.lower())
def _docker_expand_user(self, string, any_char=False):
user_pos = string.find("~")
if user_pos > -1:
if self.home_dir is None:
self.home_dir = self.ssh_command_runner.run(
"docker exec {} env | grep HOME | cut -d'=' -f2".format(
self.container_name),
with_output=True).decode("utf-8").strip()
if any_char:
return string.replace("~/", self.home_dir + "/")
elif not any_char and user_pos == 0:
return string.replace("~", self.home_dir, 1)
return string
def run_init(self, *, as_head, file_mounts):
BOOTSTRAP_MOUNTS = [
"~/ray_bootstrap_config.yaml", "~/ray_bootstrap_key.pem"
]
image = self.docker_config.get("image")
image = self.docker_config.get(
f"{'head' if as_head else 'worker'}_image", image)
self._check_docker_installed()
if self.docker_config.get("pull_before_run", True):
assert image, "Image must be included in config if " + \
"pull_before_run is specified"
self.run("docker pull {}".format(image), run_env="host")
# Bootstrap files cannot be bind mounted because docker opens the
# underlying inode. When the file is switched, docker becomes outdated.
cleaned_bind_mounts = file_mounts.copy()
for mnt in BOOTSTRAP_MOUNTS:
cleaned_bind_mounts.pop(mnt, None)
start_command = docker_start_cmds(
self.ssh_command_runner.ssh_user, image, cleaned_bind_mounts,
self.container_name,
self.docker_config.get("run_options", []) + self.docker_config.get(
f"{'head' if as_head else 'worker'}_run_options", []))
if not self._check_container_status():
self.run(start_command, run_env="host")
else:
running_image = self.run(
check_docker_image(self.container_name),
with_output=True,
run_env="host").decode("utf-8").strip()
if running_image != image:
logger.error(f"A container with name {self.container_name} " +
f"is running image {running_image} instead " +
f"of {image} (which was provided in the YAML")
mounts = self.run(
check_bind_mounts_cmd(self.container_name),
with_output=True,
run_env="host").decode("utf-8").strip()
try:
active_mounts = json.loads(mounts)
active_remote_mounts = [
mnt["Destination"] for mnt in active_mounts
]
# Ignore ray bootstrap files.
for remote, local in cleaned_bind_mounts.items():
remote = self._docker_expand_user(remote)
if remote not in active_remote_mounts:
cli_logger.error(
"Please ray stop & restart cluster to "
f"allow mount {remote}:{local} to take hold")
except json.JSONDecodeError:
cli_logger.verbose(
"Unable to check if file_mounts specified in the YAML "
"differ from those on the running container.")
# Explicitly copy in ray bootstrap files.
for mount in BOOTSTRAP_MOUNTS:
if mount in file_mounts:
self.ssh_command_runner.run(
"docker cp {src} {container}:{dst}".format(
src=os.path.join(DOCKER_MOUNT_PREFIX, mount),
container=self.container_name,
dst=self._docker_expand_user(mount)))
self.initialized = True
| 39.750696 | 79 | 0.566063 | from getpass import getuser
from shlex import quote
from typing import Dict
import click
import hashlib
import json
import logging
import os
import subprocess
import sys
import time
import warnings
from ray.autoscaler.command_runner import CommandRunnerInterface
from ray.autoscaler._private.docker import check_bind_mounts_cmd, \
check_docker_running_cmd, \
check_docker_image, \
docker_start_cmds, \
DOCKER_MOUNT_PREFIX, \
with_docker_exec
from ray.autoscaler._private.log_timer import LogTimer
from ray.autoscaler._private.subprocess_output_util import (
run_cmd_redirected, ProcessRunnerError, is_output_redirected)
from ray.autoscaler._private.cli_logger import cli_logger
import colorful as cf
logger = logging.getLogger(__name__)
NODE_START_WAIT_S = 300
HASH_MAX_LENGTH = 10
KUBECTL_RSYNC = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "kubernetes/kubectl-rsync.sh")
_config = {"use_login_shells": True, "silent_rsync": True}
def is_rsync_silent():
return _config["silent_rsync"]
def set_rsync_silent(val):
_config["silent_rsync"] = val
def is_using_login_shells():
return _config["use_login_shells"]
def set_using_login_shells(val):
_config["use_login_shells"] = val
def _with_environment_variables(cmd: str,
environment_variables: Dict[str, object]):
as_strings = []
for key, val in environment_variables.items():
val = json.dumps(val, separators=(",", ":"))
s = "export {}={};".format(key, quote(val))
as_strings.append(s)
all_vars = "".join(as_strings)
return all_vars + cmd
def _with_interactive(cmd):
force_interactive = (
f"true && source ~/.bashrc && "
f"export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && ({cmd})")
return ["bash", "--login", "-c", "-i", quote(force_interactive)]
class KubernetesCommandRunner(CommandRunnerInterface):
def __init__(self, log_prefix, namespace, node_id, auth_config,
process_runner):
self.log_prefix = log_prefix
self.process_runner = process_runner
self.node_id = str(node_id)
self.namespace = namespace
self.kubectl = ["kubectl", "-n", self.namespace]
def run(
self,
cmd=None,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto",
ssh_options_override_ssh_key="",
shutdown_after_run=False,
):
if shutdown_after_run:
cmd += "; sudo shutdown -h now"
if cmd and port_forward:
raise Exception(
"exec with Kubernetes can't forward ports and execute"
"commands together.")
if port_forward:
if not isinstance(port_forward, list):
port_forward = [port_forward]
port_forward_cmd = self.kubectl + [
"port-forward",
self.node_id,
] + [
"{}:{}".format(local, remote) for local, remote in port_forward
]
logger.info("Port forwarding with: {}".format(
" ".join(port_forward_cmd)))
port_forward_process = subprocess.Popen(port_forward_cmd)
port_forward_process.wait()
# We should never get here, this indicates that port forwarding
# failed, likely because we couldn't bind to a port.
pout, perr = port_forward_process.communicate()
exception_str = " ".join(
port_forward_cmd) + " failed with error: " + perr
raise Exception(exception_str)
else:
final_cmd = self.kubectl + ["exec", "-it"]
final_cmd += [
self.node_id,
"--",
]
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
cmd = _with_interactive(cmd)
cmd_prefix = " ".join(final_cmd)
final_cmd += cmd
final_cmd = " ".join(final_cmd)
logger.info(self.log_prefix + "Running {}".format(final_cmd))
try:
if with_output:
return self.process_runner.check_output(
final_cmd, shell=True)
else:
self.process_runner.check_call(final_cmd, shell=True)
except subprocess.CalledProcessError:
if exit_on_fail:
quoted_cmd = cmd_prefix + quote(" ".join(cmd))
logger.error(
self.log_prefix +
"Command failed: \n\n {}\n".format(quoted_cmd))
sys.exit(1)
else:
raise
def run_rsync_up(self, source, target, options=None):
if target.startswith("~"):
target = "/root" + target[1:]
try:
self.process_runner.check_call([
KUBECTL_RSYNC,
"-avz",
source,
"{}@{}:{}".format(self.node_id, self.namespace, target),
])
except Exception as e:
warnings.warn(
self.log_prefix +
"rsync failed: '{}'. Falling back to 'kubectl cp'".format(e),
UserWarning)
if target.startswith("~"):
target = "/root" + target[1:]
self.process_runner.check_call(self.kubectl + [
"cp", source, "{}/{}:{}".format(self.namespace, self.node_id,
target)
])
def run_rsync_down(self, source, target, options=None):
if target.startswith("~"):
target = "/root" + target[1:]
try:
self.process_runner.check_call([
KUBECTL_RSYNC,
"-avz",
"{}@{}:{}".format(self.node_id, self.namespace, source),
target,
])
except Exception as e:
warnings.warn(
self.log_prefix +
"rsync failed: '{}'. Falling back to 'kubectl cp'".format(e),
UserWarning)
if target.startswith("~"):
target = "/root" + target[1:]
self.process_runner.check_call(self.kubectl + [
"cp", "{}/{}:{}".format(self.namespace, self.node_id, source),
target
])
def remote_shell_command_str(self):
return "{} exec -it {} bash".format(" ".join(self.kubectl),
self.node_id)
class SSHOptions:
def __init__(self, ssh_key, control_path=None, **kwargs):
self.ssh_key = ssh_key
self.arg_dict = {
"StrictHostKeyChecking": "no",
"UserKnownHostsFile": os.devnull,
"IdentitiesOnly": "yes",
"ExitOnForwardFailure": "yes",
"ServerAliveInterval": 5,
"ServerAliveCountMax": 3
}
if control_path:
self.arg_dict.update({
"ControlMaster": "auto",
"ControlPath": "{}/%C".format(control_path),
"ControlPersist": "10s",
})
self.arg_dict.update(kwargs)
def to_ssh_options_list(self, *, timeout=60):
self.arg_dict["ConnectTimeout"] = "{}s".format(timeout)
ssh_key_option = ["-i", self.ssh_key] if self.ssh_key else []
return ssh_key_option + [
x for y in (["-o", "{}={}".format(k, v)]
for k, v in self.arg_dict.items()
if v is not None) for x in y
]
class SSHCommandRunner(CommandRunnerInterface):
def __init__(self, log_prefix, node_id, provider, auth_config,
cluster_name, process_runner, use_internal_ip):
ssh_control_hash = hashlib.md5(cluster_name.encode()).hexdigest()
ssh_user_hash = hashlib.md5(getuser().encode()).hexdigest()
ssh_control_path = "/tmp/ray_ssh_{}/{}".format(
ssh_user_hash[:HASH_MAX_LENGTH],
ssh_control_hash[:HASH_MAX_LENGTH])
self.log_prefix = log_prefix
self.process_runner = process_runner
self.node_id = node_id
self.use_internal_ip = use_internal_ip
self.provider = provider
self.ssh_private_key = auth_config.get("ssh_private_key")
self.ssh_user = auth_config["ssh_user"]
self.ssh_control_path = ssh_control_path
self.ssh_ip = None
self.ssh_proxy_command = auth_config.get("ssh_proxy_command", None)
self.ssh_options = SSHOptions(
self.ssh_private_key,
self.ssh_control_path,
ProxyCommand=self.ssh_proxy_command)
def _get_node_ip(self):
if self.use_internal_ip:
return self.provider.internal_ip(self.node_id)
else:
return self.provider.external_ip(self.node_id)
def _wait_for_ip(self, deadline):
ip = self._get_node_ip()
if ip is not None:
cli_logger.labeled_value("Fetched IP", ip)
return ip
interval = 10
with cli_logger.timed("Waiting for IP"):
while time.time() < deadline and \
not self.provider.is_terminated(self.node_id):
cli_logger.old_info(logger, "{}Waiting for IP...",
self.log_prefix)
ip = self._get_node_ip()
if ip is not None:
cli_logger.labeled_value("Received", ip)
return ip
cli_logger.print("Not yet available, retrying in {} seconds",
cf.bold(str(interval)))
time.sleep(interval)
return None
def _set_ssh_ip_if_required(self):
if self.ssh_ip is not None:
return
deadline = time.time() + NODE_START_WAIT_S
with LogTimer(self.log_prefix + "Got IP"):
ip = self._wait_for_ip(deadline)
cli_logger.doassert(ip is not None,
"Could not get node IP.") # todo: msg
assert ip is not None, "Unable to find IP of node"
self.ssh_ip = ip
# This should run before any SSH commands and therefore ensure that
# the ControlPath directory exists, allowing SSH to maintain
# persistent sessions later on.
try:
os.makedirs(self.ssh_control_path, mode=0o700, exist_ok=True)
except OSError as e:
cli_logger.warning("{}", str(e)) # todo: msg
cli_logger.old_warning(logger, "{}", str(e))
def _run_helper(self,
final_cmd,
with_output=False,
exit_on_fail=False,
silent=False):
try:
# For now, if the output is needed we just skip the new logic.
# In the future we could update the new logic to support
# capturing output, but it is probably not needed.
if not cli_logger.old_style and not with_output:
return run_cmd_redirected(
final_cmd,
process_runner=self.process_runner,
silent=silent,
use_login_shells=is_using_login_shells())
if with_output:
return self.process_runner.check_output(final_cmd)
else:
return self.process_runner.check_call(final_cmd)
except subprocess.CalledProcessError as e:
quoted_cmd = " ".join(final_cmd[:-1] + [quote(final_cmd[-1])])
if not cli_logger.old_style and not is_using_login_shells():
raise ProcessRunnerError(
"Command failed",
"ssh_command_failed",
code=e.returncode,
command=quoted_cmd)
if exit_on_fail:
raise click.ClickException(
"Command failed:\n\n {}\n".format(quoted_cmd)) from None
else:
fail_msg = "SSH command failed."
if is_output_redirected():
fail_msg += " See above for the output from the failure."
raise click.ClickException(fail_msg) from None
def run(
self,
cmd,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto", # Unused argument.
ssh_options_override_ssh_key="",
shutdown_after_run=False,
):
if shutdown_after_run:
cmd += "; sudo shutdown -h now"
if ssh_options_override_ssh_key:
ssh_options = SSHOptions(ssh_options_override_ssh_key)
else:
ssh_options = self.ssh_options
assert isinstance(
ssh_options, SSHOptions
), "ssh_options must be of type SSHOptions, got {}".format(
type(ssh_options))
self._set_ssh_ip_if_required()
if is_using_login_shells():
ssh = ["ssh", "-tt"]
else:
ssh = ["ssh"]
if port_forward:
with cli_logger.group("Forwarding ports"):
if not isinstance(port_forward, list):
port_forward = [port_forward]
for local, remote in port_forward:
cli_logger.verbose(
"Forwarding port {} to port {} on localhost.",
cf.bold(local), cf.bold(remote)) # todo: msg
cli_logger.old_info(logger,
"{}Forwarding {} -> localhost:{}",
self.log_prefix, local, remote)
ssh += ["-L", "{}:localhost:{}".format(remote, local)]
final_cmd = ssh + ssh_options.to_ssh_options_list(timeout=timeout) + [
"{}@{}".format(self.ssh_user, self.ssh_ip)
]
if cmd:
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
if is_using_login_shells():
final_cmd += _with_interactive(cmd)
else:
final_cmd += [cmd]
cli_logger.old_info(logger, "{}Running {}", self.log_prefix,
" ".join(final_cmd))
else:
# We do this because `-o ControlMaster` causes the `-N` flag to
# still create an interactive shell in some ssh versions.
final_cmd.append("while true; do sleep 86400; done")
cli_logger.verbose("Running `{}`", cf.bold(cmd))
with cli_logger.indented():
cli_logger.very_verbose("Full command is `{}`",
cf.bold(" ".join(final_cmd)))
if cli_logger.verbosity > 0:
with cli_logger.indented():
return self._run_helper(final_cmd, with_output, exit_on_fail)
else:
return self._run_helper(final_cmd, with_output, exit_on_fail)
def run_rsync_up(self, source, target, options=None):
self._set_ssh_ip_if_required()
command = [
"rsync", "--rsh",
subprocess.list2cmdline(
["ssh"] + self.ssh_options.to_ssh_options_list(timeout=120)),
"-avz", source, "{}@{}:{}".format(self.ssh_user, self.ssh_ip,
target)
]
cli_logger.verbose("Running `{}`", cf.bold(" ".join(command)))
self._run_helper(command, silent=is_rsync_silent())
def run_rsync_down(self, source, target, options=None):
self._set_ssh_ip_if_required()
command = [
"rsync", "--rsh",
subprocess.list2cmdline(
["ssh"] + self.ssh_options.to_ssh_options_list(timeout=120)),
"-avz", "{}@{}:{}".format(self.ssh_user, self.ssh_ip,
source), target
]
cli_logger.verbose("Running `{}`", cf.bold(" ".join(command)))
self._run_helper(command, silent=is_rsync_silent())
def remote_shell_command_str(self):
if self.ssh_private_key:
return "ssh -o IdentitiesOnly=yes -i {} {}@{}\n".format(
self.ssh_private_key, self.ssh_user, self.ssh_ip)
else:
return "ssh -o IdentitiesOnly=yes {}@{}\n".format(
self.ssh_user, self.ssh_ip)
class DockerCommandRunner(CommandRunnerInterface):
def __init__(self, docker_config, **common_args):
self.ssh_command_runner = SSHCommandRunner(**common_args)
self.container_name = docker_config["container_name"]
self.docker_config = docker_config
self.home_dir = None
self.initialized = False
def run(
self,
cmd,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto",
ssh_options_override_ssh_key="",
shutdown_after_run=False,
):
if run_env == "auto":
run_env = "host" if cmd.find("docker") == 0 else "docker"
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
if run_env == "docker":
cmd = self._docker_expand_user(cmd, any_char=True)
cmd = " ".join(_with_interactive(cmd))
cmd = with_docker_exec(
[cmd],
container_name=self.container_name,
with_interactive=True)[0]
if shutdown_after_run:
# sudo shutdown should run after `with_docker_exec` command above
cmd += "; sudo shutdown -h now"
# Do not pass shutdown_after_run argument to ssh_command_runner.run()
# since it is handled above.
return self.ssh_command_runner.run(
cmd,
timeout=timeout,
exit_on_fail=exit_on_fail,
port_forward=port_forward,
with_output=with_output,
ssh_options_override_ssh_key=ssh_options_override_ssh_key)
def run_rsync_up(self, source, target, options=None):
options = options or {}
host_destination = os.path.join(DOCKER_MOUNT_PREFIX,
target.lstrip("/"))
self.ssh_command_runner.run(
f"mkdir -p {os.path.dirname(host_destination.rstrip('/'))}")
self.ssh_command_runner.run_rsync_up(
source, host_destination, options=None)
if self._check_container_status() and not options.get(
"file_mount", False):
if os.path.isdir(source):
# Adding a "." means that docker copies the *contents*
# Without it, docker copies the source *into* the target
host_destination += "/."
self.ssh_command_runner.run("docker cp {} {}:{}".format(
host_destination, self.container_name,
self._docker_expand_user(target)))
def run_rsync_down(self, source, target, options=None):
options = options or {}
host_source = os.path.join(DOCKER_MOUNT_PREFIX, source.lstrip("/"))
self.ssh_command_runner.run(
f"mkdir -p {os.path.dirname(host_source.rstrip('/'))}")
if source[-1] == "/":
source += "."
# Adding a "." means that docker copies the *contents*
# Without it, docker copies the source *into* the target
if not options.get("file_mount", False):
self.ssh_command_runner.run("docker cp {}:{} {}".format(
self.container_name, self._docker_expand_user(source),
host_source))
self.ssh_command_runner.run_rsync_down(
host_source, target, options=None)
def remote_shell_command_str(self):
inner_str = self.ssh_command_runner.remote_shell_command_str().replace(
"ssh", "ssh -tt", 1).strip("\n")
return inner_str + " docker exec -it {} /bin/bash\n".format(
self.container_name)
def _check_docker_installed(self):
no_exist = "NoExist"
output = self.ssh_command_runner.run(
f"command -v docker || echo '{no_exist}'", with_output=True)
cleaned_output = output.decode().strip()
if no_exist in cleaned_output or "docker" not in cleaned_output:
install_commands = [
"curl -fsSL https://get.docker.com -o get-docker.sh",
"sudo sh get-docker.sh", "sudo usermod -aG docker $USER",
"sudo systemctl restart docker -f"
]
logger.error(
"Docker not installed. You can install Docker by adding the "
"following commands to 'initialization_commands':\n" +
"\n".join(install_commands))
def _check_container_status(self):
if self.initialized:
return True
output = self.ssh_command_runner.run(
check_docker_running_cmd(self.container_name),
with_output=True).decode("utf-8").strip()
# Checks for the false positive where "true" is in the container name
return ("true" in output.lower()
and "no such object" not in output.lower())
def _docker_expand_user(self, string, any_char=False):
user_pos = string.find("~")
if user_pos > -1:
if self.home_dir is None:
self.home_dir = self.ssh_command_runner.run(
"docker exec {} env | grep HOME | cut -d'=' -f2".format(
self.container_name),
with_output=True).decode("utf-8").strip()
if any_char:
return string.replace("~/", self.home_dir + "/")
elif not any_char and user_pos == 0:
return string.replace("~", self.home_dir, 1)
return string
def run_init(self, *, as_head, file_mounts):
BOOTSTRAP_MOUNTS = [
"~/ray_bootstrap_config.yaml", "~/ray_bootstrap_key.pem"
]
image = self.docker_config.get("image")
image = self.docker_config.get(
f"{'head' if as_head else 'worker'}_image", image)
self._check_docker_installed()
if self.docker_config.get("pull_before_run", True):
assert image, "Image must be included in config if " + \
"pull_before_run is specified"
self.run("docker pull {}".format(image), run_env="host")
# Bootstrap files cannot be bind mounted because docker opens the
# underlying inode. When the file is switched, docker becomes outdated.
cleaned_bind_mounts = file_mounts.copy()
for mnt in BOOTSTRAP_MOUNTS:
cleaned_bind_mounts.pop(mnt, None)
start_command = docker_start_cmds(
self.ssh_command_runner.ssh_user, image, cleaned_bind_mounts,
self.container_name,
self.docker_config.get("run_options", []) + self.docker_config.get(
f"{'head' if as_head else 'worker'}_run_options", []))
if not self._check_container_status():
self.run(start_command, run_env="host")
else:
running_image = self.run(
check_docker_image(self.container_name),
with_output=True,
run_env="host").decode("utf-8").strip()
if running_image != image:
logger.error(f"A container with name {self.container_name} " +
f"is running image {running_image} instead " +
f"of {image} (which was provided in the YAML")
mounts = self.run(
check_bind_mounts_cmd(self.container_name),
with_output=True,
run_env="host").decode("utf-8").strip()
try:
active_mounts = json.loads(mounts)
active_remote_mounts = [
mnt["Destination"] for mnt in active_mounts
]
# Ignore ray bootstrap files.
for remote, local in cleaned_bind_mounts.items():
remote = self._docker_expand_user(remote)
if remote not in active_remote_mounts:
cli_logger.error(
"Please ray stop & restart cluster to "
f"allow mount {remote}:{local} to take hold")
except json.JSONDecodeError:
cli_logger.verbose(
"Unable to check if file_mounts specified in the YAML "
"differ from those on the running container.")
# Explicitly copy in ray bootstrap files.
for mount in BOOTSTRAP_MOUNTS:
if mount in file_mounts:
self.ssh_command_runner.run(
"docker cp {src} {container}:{dst}".format(
src=os.path.join(DOCKER_MOUNT_PREFIX, mount),
container=self.container_name,
dst=self._docker_expand_user(mount)))
self.initialized = True
| true | true |
f72c13cb90eedb34f57932aeb5a75dd0d3d17462 | 9,968 | py | Python | paddlex/ppdet/modeling/assigners/atss_assigner.py | cheneyveron/PaddleX | 86f73fc6a66b12c638f642524bfd1cf730e26c4b | [
"Apache-2.0"
] | 8 | 2020-03-11T08:12:19.000Z | 2020-03-18T08:33:56.000Z | paddlex/ppdet/modeling/assigners/atss_assigner.py | cheneyveron/PaddleX | 86f73fc6a66b12c638f642524bfd1cf730e26c4b | [
"Apache-2.0"
] | 1 | 2020-03-15T13:05:43.000Z | 2020-03-15T13:05:43.000Z | paddlex/ppdet/modeling/assigners/atss_assigner.py | cheneyveron/PaddleX | 86f73fc6a66b12c638f642524bfd1cf730e26c4b | [
"Apache-2.0"
] | 2 | 2020-03-15T11:53:54.000Z | 2020-03-24T07:27:09.000Z | # Copyright (c) 2021 PaddlePaddle 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlex.ppdet.core.workspace import register
from ..ops import iou_similarity
from ..bbox_utils import bbox_center
from .utils import (pad_gt, check_points_inside_bboxes, compute_max_iou_anchor,
compute_max_iou_gt)
@register
class ATSSAssigner(nn.Layer):
"""Bridging the Gap Between Anchor-based and Anchor-free Detection
via Adaptive Training Sample Selection
"""
__shared__ = ['num_classes']
def __init__(self,
topk=9,
num_classes=80,
force_gt_matching=False,
eps=1e-9):
super(ATSSAssigner, self).__init__()
self.topk = topk
self.num_classes = num_classes
self.force_gt_matching = force_gt_matching
self.eps = eps
def _gather_topk_pyramid(self, gt2anchor_distances, num_anchors_list,
pad_gt_mask):
pad_gt_mask = pad_gt_mask.tile([1, 1, self.topk]).astype(paddle.bool)
gt2anchor_distances_list = paddle.split(
gt2anchor_distances, num_anchors_list, axis=-1)
num_anchors_index = np.cumsum(num_anchors_list).tolist()
num_anchors_index = [0, ] + num_anchors_index[:-1]
is_in_topk_list = []
topk_idxs_list = []
for distances, anchors_index in zip(gt2anchor_distances_list,
num_anchors_index):
num_anchors = distances.shape[-1]
topk_metrics, topk_idxs = paddle.topk(
distances, self.topk, axis=-1, largest=False)
topk_idxs_list.append(topk_idxs + anchors_index)
topk_idxs = paddle.where(pad_gt_mask, topk_idxs,
paddle.zeros_like(topk_idxs))
is_in_topk = F.one_hot(topk_idxs, num_anchors).sum(axis=-2)
is_in_topk = paddle.where(is_in_topk > 1,
paddle.zeros_like(is_in_topk),
is_in_topk)
is_in_topk_list.append(
is_in_topk.astype(gt2anchor_distances.dtype))
is_in_topk_list = paddle.concat(is_in_topk_list, axis=-1)
topk_idxs_list = paddle.concat(topk_idxs_list, axis=-1)
return is_in_topk_list, topk_idxs_list
@paddle.no_grad()
def forward(self,
anchor_bboxes,
num_anchors_list,
gt_labels,
gt_bboxes,
bg_index,
gt_scores=None):
r"""This code is based on
https://github.com/fcjian/TOOD/blob/master/mmdet/core/bbox/assigners/atss_assigner.py
The assignment is done in following steps
1. compute iou between all bbox (bbox of all pyramid levels) and gt
2. compute center distance between all bbox and gt
3. on each pyramid level, for each gt, select k bbox whose center
are closest to the gt center, so we total select k*l bbox as
candidates for each gt
4. get corresponding iou for the these candidates, and compute the
mean and std, set mean + std as the iou threshold
5. select these candidates whose iou are greater than or equal to
the threshold as positive
6. limit the positive sample's center in gt
7. if an anchor box is assigned to multiple gts, the one with the
highest iou will be selected.
Args:
anchor_bboxes (Tensor, float32): pre-defined anchors, shape(L, 4),
"xmin, xmax, ymin, ymax" format
num_anchors_list (List): num of anchors in each level
gt_labels (Tensor|List[Tensor], int64): Label of gt_bboxes, shape(B, n, 1)
gt_bboxes (Tensor|List[Tensor], float32): Ground truth bboxes, shape(B, n, 4)
bg_index (int): background index
gt_scores (Tensor|List[Tensor]|None, float32) Score of gt_bboxes,
shape(B, n, 1), if None, then it will initialize with one_hot label
Returns:
assigned_labels (Tensor): (B, L)
assigned_bboxes (Tensor): (B, L, 4)
assigned_scores (Tensor): (B, L, C)
"""
gt_labels, gt_bboxes, pad_gt_scores, pad_gt_mask = pad_gt(
gt_labels, gt_bboxes, gt_scores)
assert gt_labels.ndim == gt_bboxes.ndim and \
gt_bboxes.ndim == 3
num_anchors, _ = anchor_bboxes.shape
batch_size, num_max_boxes, _ = gt_bboxes.shape
# negative batch
if num_max_boxes == 0:
assigned_labels = paddle.full([batch_size, num_anchors], bg_index)
assigned_bboxes = paddle.zeros([batch_size, num_anchors, 4])
assigned_scores = paddle.zeros(
[batch_size, num_anchors, self.num_classes])
return assigned_labels, assigned_bboxes, assigned_scores
# 1. compute iou between gt and anchor bbox, [B, n, L]
ious = iou_similarity(gt_bboxes.reshape([-1, 4]), anchor_bboxes)
ious = ious.reshape([batch_size, -1, num_anchors])
# 2. compute center distance between all anchors and gt, [B, n, L]
gt_centers = bbox_center(gt_bboxes.reshape([-1, 4])).unsqueeze(1)
anchor_centers = bbox_center(anchor_bboxes)
gt2anchor_distances = (gt_centers - anchor_centers.unsqueeze(0)) \
.norm(2, axis=-1).reshape([batch_size, -1, num_anchors])
# 3. on each pyramid level, selecting topk closest candidates
# based on the center distance, [B, n, L]
is_in_topk, topk_idxs = self._gather_topk_pyramid(
gt2anchor_distances, num_anchors_list, pad_gt_mask)
# 4. get corresponding iou for the these candidates, and compute the
# mean and std, 5. set mean + std as the iou threshold
iou_candidates = ious * is_in_topk
iou_threshold = paddle.index_sample(
iou_candidates.flatten(stop_axis=-2),
topk_idxs.flatten(stop_axis=-2))
iou_threshold = iou_threshold.reshape([batch_size, num_max_boxes, -1])
iou_threshold = iou_threshold.mean(axis=-1, keepdim=True) + \
iou_threshold.std(axis=-1, keepdim=True)
is_in_topk = paddle.where(
iou_candidates > iou_threshold.tile([1, 1, num_anchors]),
is_in_topk, paddle.zeros_like(is_in_topk))
# 6. check the positive sample's center in gt, [B, n, L]
is_in_gts = check_points_inside_bboxes(anchor_centers, gt_bboxes)
# select positive sample, [B, n, L]
mask_positive = is_in_topk * is_in_gts * pad_gt_mask
# 7. if an anchor box is assigned to multiple gts,
# the one with the highest iou will be selected.
mask_positive_sum = mask_positive.sum(axis=-2)
if mask_positive_sum.max() > 1:
mask_multiple_gts = (mask_positive_sum.unsqueeze(1) > 1).tile(
[1, num_max_boxes, 1])
is_max_iou = compute_max_iou_anchor(ious)
mask_positive = paddle.where(mask_multiple_gts, is_max_iou,
mask_positive)
mask_positive_sum = mask_positive.sum(axis=-2)
# 8. make sure every gt_bbox matches the anchor
if self.force_gt_matching:
is_max_iou = compute_max_iou_gt(ious) * pad_gt_mask
mask_max_iou = (is_max_iou.sum(-2, keepdim=True) == 1).tile(
[1, num_max_boxes, 1])
mask_positive = paddle.where(mask_max_iou, is_max_iou,
mask_positive)
mask_positive_sum = mask_positive.sum(axis=-2)
assigned_gt_index = mask_positive.argmax(axis=-2)
assert mask_positive_sum.max() == 1, \
("one anchor just assign one gt, but received not equals 1. "
"Received: %f" % mask_positive_sum.max().item())
# assigned target
batch_ind = paddle.arange(
end=batch_size, dtype=gt_labels.dtype).unsqueeze(-1)
assigned_gt_index = assigned_gt_index + batch_ind * num_max_boxes
assigned_labels = paddle.gather(
gt_labels.flatten(), assigned_gt_index.flatten(), axis=0)
assigned_labels = assigned_labels.reshape([batch_size, num_anchors])
assigned_labels = paddle.where(
mask_positive_sum > 0, assigned_labels,
paddle.full_like(assigned_labels, bg_index))
assigned_bboxes = paddle.gather(
gt_bboxes.reshape([-1, 4]), assigned_gt_index.flatten(), axis=0)
assigned_bboxes = assigned_bboxes.reshape([batch_size, num_anchors, 4])
assigned_scores = F.one_hot(assigned_labels, self.num_classes)
if gt_scores is not None:
gather_scores = paddle.gather(
pad_gt_scores.flatten(), assigned_gt_index.flatten(), axis=0)
gather_scores = gather_scores.reshape([batch_size, num_anchors])
gather_scores = paddle.where(mask_positive_sum > 0, gather_scores,
paddle.zeros_like(gather_scores))
assigned_scores *= gather_scores.unsqueeze(-1)
return assigned_labels, assigned_bboxes, assigned_scores
| 47.018868 | 97 | 0.634129 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlex.ppdet.core.workspace import register
from ..ops import iou_similarity
from ..bbox_utils import bbox_center
from .utils import (pad_gt, check_points_inside_bboxes, compute_max_iou_anchor,
compute_max_iou_gt)
@register
class ATSSAssigner(nn.Layer):
__shared__ = ['num_classes']
def __init__(self,
topk=9,
num_classes=80,
force_gt_matching=False,
eps=1e-9):
super(ATSSAssigner, self).__init__()
self.topk = topk
self.num_classes = num_classes
self.force_gt_matching = force_gt_matching
self.eps = eps
def _gather_topk_pyramid(self, gt2anchor_distances, num_anchors_list,
pad_gt_mask):
pad_gt_mask = pad_gt_mask.tile([1, 1, self.topk]).astype(paddle.bool)
gt2anchor_distances_list = paddle.split(
gt2anchor_distances, num_anchors_list, axis=-1)
num_anchors_index = np.cumsum(num_anchors_list).tolist()
num_anchors_index = [0, ] + num_anchors_index[:-1]
is_in_topk_list = []
topk_idxs_list = []
for distances, anchors_index in zip(gt2anchor_distances_list,
num_anchors_index):
num_anchors = distances.shape[-1]
topk_metrics, topk_idxs = paddle.topk(
distances, self.topk, axis=-1, largest=False)
topk_idxs_list.append(topk_idxs + anchors_index)
topk_idxs = paddle.where(pad_gt_mask, topk_idxs,
paddle.zeros_like(topk_idxs))
is_in_topk = F.one_hot(topk_idxs, num_anchors).sum(axis=-2)
is_in_topk = paddle.where(is_in_topk > 1,
paddle.zeros_like(is_in_topk),
is_in_topk)
is_in_topk_list.append(
is_in_topk.astype(gt2anchor_distances.dtype))
is_in_topk_list = paddle.concat(is_in_topk_list, axis=-1)
topk_idxs_list = paddle.concat(topk_idxs_list, axis=-1)
return is_in_topk_list, topk_idxs_list
@paddle.no_grad()
def forward(self,
anchor_bboxes,
num_anchors_list,
gt_labels,
gt_bboxes,
bg_index,
gt_scores=None):
gt_labels, gt_bboxes, pad_gt_scores, pad_gt_mask = pad_gt(
gt_labels, gt_bboxes, gt_scores)
assert gt_labels.ndim == gt_bboxes.ndim and \
gt_bboxes.ndim == 3
num_anchors, _ = anchor_bboxes.shape
batch_size, num_max_boxes, _ = gt_bboxes.shape
if num_max_boxes == 0:
assigned_labels = paddle.full([batch_size, num_anchors], bg_index)
assigned_bboxes = paddle.zeros([batch_size, num_anchors, 4])
assigned_scores = paddle.zeros(
[batch_size, num_anchors, self.num_classes])
return assigned_labels, assigned_bboxes, assigned_scores
ious = iou_similarity(gt_bboxes.reshape([-1, 4]), anchor_bboxes)
ious = ious.reshape([batch_size, -1, num_anchors])
gt_centers = bbox_center(gt_bboxes.reshape([-1, 4])).unsqueeze(1)
anchor_centers = bbox_center(anchor_bboxes)
gt2anchor_distances = (gt_centers - anchor_centers.unsqueeze(0)) \
.norm(2, axis=-1).reshape([batch_size, -1, num_anchors])
is_in_topk, topk_idxs = self._gather_topk_pyramid(
gt2anchor_distances, num_anchors_list, pad_gt_mask)
iou_candidates = ious * is_in_topk
iou_threshold = paddle.index_sample(
iou_candidates.flatten(stop_axis=-2),
topk_idxs.flatten(stop_axis=-2))
iou_threshold = iou_threshold.reshape([batch_size, num_max_boxes, -1])
iou_threshold = iou_threshold.mean(axis=-1, keepdim=True) + \
iou_threshold.std(axis=-1, keepdim=True)
is_in_topk = paddle.where(
iou_candidates > iou_threshold.tile([1, 1, num_anchors]),
is_in_topk, paddle.zeros_like(is_in_topk))
is_in_gts = check_points_inside_bboxes(anchor_centers, gt_bboxes)
# select positive sample, [B, n, L]
mask_positive = is_in_topk * is_in_gts * pad_gt_mask
# 7. if an anchor box is assigned to multiple gts,
# the one with the highest iou will be selected.
mask_positive_sum = mask_positive.sum(axis=-2)
if mask_positive_sum.max() > 1:
mask_multiple_gts = (mask_positive_sum.unsqueeze(1) > 1).tile(
[1, num_max_boxes, 1])
is_max_iou = compute_max_iou_anchor(ious)
mask_positive = paddle.where(mask_multiple_gts, is_max_iou,
mask_positive)
mask_positive_sum = mask_positive.sum(axis=-2)
# 8. make sure every gt_bbox matches the anchor
if self.force_gt_matching:
is_max_iou = compute_max_iou_gt(ious) * pad_gt_mask
mask_max_iou = (is_max_iou.sum(-2, keepdim=True) == 1).tile(
[1, num_max_boxes, 1])
mask_positive = paddle.where(mask_max_iou, is_max_iou,
mask_positive)
mask_positive_sum = mask_positive.sum(axis=-2)
assigned_gt_index = mask_positive.argmax(axis=-2)
assert mask_positive_sum.max() == 1, \
("one anchor just assign one gt, but received not equals 1. "
"Received: %f" % mask_positive_sum.max().item())
# assigned target
batch_ind = paddle.arange(
end=batch_size, dtype=gt_labels.dtype).unsqueeze(-1)
assigned_gt_index = assigned_gt_index + batch_ind * num_max_boxes
assigned_labels = paddle.gather(
gt_labels.flatten(), assigned_gt_index.flatten(), axis=0)
assigned_labels = assigned_labels.reshape([batch_size, num_anchors])
assigned_labels = paddle.where(
mask_positive_sum > 0, assigned_labels,
paddle.full_like(assigned_labels, bg_index))
assigned_bboxes = paddle.gather(
gt_bboxes.reshape([-1, 4]), assigned_gt_index.flatten(), axis=0)
assigned_bboxes = assigned_bboxes.reshape([batch_size, num_anchors, 4])
assigned_scores = F.one_hot(assigned_labels, self.num_classes)
if gt_scores is not None:
gather_scores = paddle.gather(
pad_gt_scores.flatten(), assigned_gt_index.flatten(), axis=0)
gather_scores = gather_scores.reshape([batch_size, num_anchors])
gather_scores = paddle.where(mask_positive_sum > 0, gather_scores,
paddle.zeros_like(gather_scores))
assigned_scores *= gather_scores.unsqueeze(-1)
return assigned_labels, assigned_bboxes, assigned_scores
| true | true |
f72c141ee52744b76809f89d01d00892da4316b0 | 1,625 | py | Python | models/heads/linear.py | lucasmtz/ACAR-Net | 08a224625f04bbf595baaeb1c79ec491642e0059 | [
"Apache-2.0"
] | null | null | null | models/heads/linear.py | lucasmtz/ACAR-Net | 08a224625f04bbf595baaeb1c79ec491642e0059 | [
"Apache-2.0"
] | null | null | null | models/heads/linear.py | lucasmtz/ACAR-Net | 08a224625f04bbf595baaeb1c79ec491642e0059 | [
"Apache-2.0"
] | null | null | null | import torch
import torch.nn as nn
import torchvision
__all__ = ["linear"]
class LinearHead(nn.Module):
def __init__(self, width, roi_spatial=7, num_classes=60, dropout=0.0, bias=False):
super().__init__()
self.roi_spatial = roi_spatial
self.roi_maxpool = nn.MaxPool2d(roi_spatial)
self.fc = nn.Linear(width, num_classes, bias=bias)
if dropout > 0:
self.dp = nn.Dropout(dropout)
else:
self.dp = None
# data: features, rois
# returns: outputs
def forward(self, data):
if not isinstance(data["features"], list):
features = [data["features"]]
else:
features = data["features"]
roi_features = []
for f in features:
sp = f.shape
h, w = sp[3:]
feats = nn.AdaptiveAvgPool3d((1, h, w))(f).view(-1, sp[1], h, w)
rois = data["rois"].clone()
rois[:, 1] = rois[:, 1] * w
rois[:, 2] = rois[:, 2] * h
rois[:, 3] = rois[:, 3] * w
rois[:, 4] = rois[:, 4] * h
rois = rois.detach()
roi_feats = torchvision.ops.roi_align(feats, rois, (self.roi_spatial, self.roi_spatial))
roi_feats = self.roi_maxpool(roi_feats).view(-1, sp[1])
roi_features.append(roi_feats)
roi_features = torch.cat(roi_features, dim=1)
if self.dp is not None:
roi_features = self.dp(roi_features)
outputs = self.fc(roi_features)
return {"outputs": outputs}
def linear(**kwargs):
model = LinearHead(**kwargs)
return model
| 28.017241 | 100 | 0.549538 | import torch
import torch.nn as nn
import torchvision
__all__ = ["linear"]
class LinearHead(nn.Module):
def __init__(self, width, roi_spatial=7, num_classes=60, dropout=0.0, bias=False):
super().__init__()
self.roi_spatial = roi_spatial
self.roi_maxpool = nn.MaxPool2d(roi_spatial)
self.fc = nn.Linear(width, num_classes, bias=bias)
if dropout > 0:
self.dp = nn.Dropout(dropout)
else:
self.dp = None
def forward(self, data):
if not isinstance(data["features"], list):
features = [data["features"]]
else:
features = data["features"]
roi_features = []
for f in features:
sp = f.shape
h, w = sp[3:]
feats = nn.AdaptiveAvgPool3d((1, h, w))(f).view(-1, sp[1], h, w)
rois = data["rois"].clone()
rois[:, 1] = rois[:, 1] * w
rois[:, 2] = rois[:, 2] * h
rois[:, 3] = rois[:, 3] * w
rois[:, 4] = rois[:, 4] * h
rois = rois.detach()
roi_feats = torchvision.ops.roi_align(feats, rois, (self.roi_spatial, self.roi_spatial))
roi_feats = self.roi_maxpool(roi_feats).view(-1, sp[1])
roi_features.append(roi_feats)
roi_features = torch.cat(roi_features, dim=1)
if self.dp is not None:
roi_features = self.dp(roi_features)
outputs = self.fc(roi_features)
return {"outputs": outputs}
def linear(**kwargs):
model = LinearHead(**kwargs)
return model
| true | true |
f72c167153faf45427e82959b2fabf65122a99b7 | 3,730 | py | Python | lib/follower.py | bopopescu/ros | 5dc6e23a280e1283de7b38f35116332a79ca33d2 | [
"MIT"
] | null | null | null | lib/follower.py | bopopescu/ros | 5dc6e23a280e1283de7b38f35116332a79ca33d2 | [
"MIT"
] | null | null | null | lib/follower.py | bopopescu/ros | 5dc6e23a280e1283de7b38f35116332a79ca33d2 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 by Murray Altheim. All rights reserved. This file is part of
# the Robot OS project and is released under the "Apache Licence, Version 2.0".
# Please see the LICENSE file included as part of this package.
#
# author: altheim
# created: 2020-03-31
# modified: 2020-03-31
# Import library functions we need
import time
from colorama import init, Fore, Style
init()
try:
import numpy
except ImportError:
exit("This script requires the numpy module\nInstall with: sudo pip3 install numpy")
from lib.tof import TimeOfFlight, Range
from lib.enums import Orientation
from lib.servo import Servo
from lib.logger import Logger, Level
# ..............................................................................
class WallFollower():
def __init__(self, config, level):
self._log = Logger('follower', Level.INFO)
self._config = config
if self._config:
self._log.info('configuration provided.')
_config = self._config['ros'].get('wall_follower')
self._port_angle = _config.get('port_angle')
self._stbd_angle = _config.get('starboard_angle')
_range_value = _config.get('tof_range')
_range = Range.from_str(_range_value)
_servo_number = _config.get('servo_number')
else:
self._log.warning('no configuration provided.')
self._port_angle = -90.0
self._stbd_angle = 90.0
_range = Range.PERFORMANCE
_servo_number = 2
# _range = Range.LONG
# _range = Range.MEDIUM
# _range = Range.SHORT
self._log.info('wall follower port angle: {:>5.2f}°; starboard angle: {:>5.2f}°'.format(self._port_angle, self._stbd_angle))
self._servo = Servo(self._config, _servo_number, level)
self._tof = TimeOfFlight(_range, Level.WARN)
self._max_retries = 10
self._enabled = False
self._closed = False
self._log.info('ready.')
# ..........................................................................
def scan(self):
mm = 0.0
wait_count = 0
while mm <= 0.1 and wait_count < self._max_retries:
mm = self._tof.read_distance()
time.sleep(0.0025)
wait_count += 1
self._log.info('distance: {:>5.0f}mm'.format(mm))
return mm
# ..........................................................................
def set_position(self, orientation):
if not self._enabled:
self._log.warning('cannot scan: disabled.')
return
if orientation == Orientation.PORT:
self._servo.set_position(self._port_angle)
elif orientation == Orientation.STBD:
self._servo.set_position(self._stbd_angle)
else:
raise ValueError('only port or starboard acceptable for wall follower orientation')
self._log.info('wall follower position set to {}.'.format(orientation))
# ..........................................................................
def enable(self):
if self._closed:
self._log.warning('cannot enable: closed.')
return
self._tof.enable()
self._enabled = True
# ..........................................................................
def disable(self):
self._enabled = False
self._servo.set_position(0.0)
self._servo.disable()
self._tof.disable()
# ..........................................................................
def close(self):
self.disable()
self._servo.close()
self._closed = True
#EOF
| 33.603604 | 132 | 0.538606 |
import time
from colorama import init, Fore, Style
init()
try:
import numpy
except ImportError:
exit("This script requires the numpy module\nInstall with: sudo pip3 install numpy")
from lib.tof import TimeOfFlight, Range
from lib.enums import Orientation
from lib.servo import Servo
from lib.logger import Logger, Level
class WallFollower():
def __init__(self, config, level):
self._log = Logger('follower', Level.INFO)
self._config = config
if self._config:
self._log.info('configuration provided.')
_config = self._config['ros'].get('wall_follower')
self._port_angle = _config.get('port_angle')
self._stbd_angle = _config.get('starboard_angle')
_range_value = _config.get('tof_range')
_range = Range.from_str(_range_value)
_servo_number = _config.get('servo_number')
else:
self._log.warning('no configuration provided.')
self._port_angle = -90.0
self._stbd_angle = 90.0
_range = Range.PERFORMANCE
_servo_number = 2
self._log.info('wall follower port angle: {:>5.2f}°; starboard angle: {:>5.2f}°'.format(self._port_angle, self._stbd_angle))
self._servo = Servo(self._config, _servo_number, level)
self._tof = TimeOfFlight(_range, Level.WARN)
self._max_retries = 10
self._enabled = False
self._closed = False
self._log.info('ready.')
def scan(self):
mm = 0.0
wait_count = 0
while mm <= 0.1 and wait_count < self._max_retries:
mm = self._tof.read_distance()
time.sleep(0.0025)
wait_count += 1
self._log.info('distance: {:>5.0f}mm'.format(mm))
return mm
def set_position(self, orientation):
if not self._enabled:
self._log.warning('cannot scan: disabled.')
return
if orientation == Orientation.PORT:
self._servo.set_position(self._port_angle)
elif orientation == Orientation.STBD:
self._servo.set_position(self._stbd_angle)
else:
raise ValueError('only port or starboard acceptable for wall follower orientation')
self._log.info('wall follower position set to {}.'.format(orientation))
def enable(self):
if self._closed:
self._log.warning('cannot enable: closed.')
return
self._tof.enable()
self._enabled = True
def disable(self):
self._enabled = False
self._servo.set_position(0.0)
self._servo.disable()
self._tof.disable()
def close(self):
self.disable()
self._servo.close()
self._closed = True
| true | true |
f72c18024f079862885e04b1184e3b2d20a53ce4 | 312 | py | Python | src/Aula15ex67Tabuada.py | maberf/python | 0d36f1586c5f52081c2b27d42a1d37cee13116b0 | [
"MIT"
] | null | null | null | src/Aula15ex67Tabuada.py | maberf/python | 0d36f1586c5f52081c2b27d42a1d37cee13116b0 | [
"MIT"
] | null | null | null | src/Aula15ex67Tabuada.py | maberf/python | 0d36f1586c5f52081c2b27d42a1d37cee13116b0 | [
"MIT"
] | null | null | null | # TABUADA
#Mostra a tabuada de vários números, um de cada vez
#O programa encerra quando o número digitado é negativo
while True:
num = int(input('Número? '))
print('=' * 10)
if num < 0:
break
for i in range(1, 11):
print(f'{num} x {i} = {num * i}')
print('='*10)
print('Fim') | 26 | 55 | 0.580128 |
while True:
num = int(input('Número? '))
print('=' * 10)
if num < 0:
break
for i in range(1, 11):
print(f'{num} x {i} = {num * i}')
print('='*10)
print('Fim') | true | true |
f72c1952b0e4622f4b26e6cbf2935e7858d86d51 | 3,061 | py | Python | BioNetGen-2.3.0/source_Atomizer/SBMLparser/atomizer/analyzeRDF.py | joseph-hellerstein/RuleBasedProgramming | fb88118ab764035979dc7c2bf8c89a7b484e4472 | [
"MIT"
] | null | null | null | BioNetGen-2.3.0/source_Atomizer/SBMLparser/atomizer/analyzeRDF.py | joseph-hellerstein/RuleBasedProgramming | fb88118ab764035979dc7c2bf8c89a7b484e4472 | [
"MIT"
] | null | null | null | BioNetGen-2.3.0/source_Atomizer/SBMLparser/atomizer/analyzeRDF.py | joseph-hellerstein/RuleBasedProgramming | fb88118ab764035979dc7c2bf8c89a7b484e4472 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 27 14:45:24 2012
@author: proto
"""
'''
this method classifies reactants according to the rdf information, and gives
us information on which reactants are the same, and how do they differ
(compartment etc)
'''
from sbml2bngl import SBML2BNGL
import libsbml
import collections
def getAnnotations(parser,stringKey=None):
annotation = parser.getSpeciesAnnotation()
annotationDictionary = collections.defaultdict(set)
for key,value in annotation.items():
annotationList = []
if annotation[key] != None:
for element in annotation[key]:
for index in range(0,element.getNumAttributes()):
if not stringKey or stringKey in element.getValue(index):
annotationList.append(element.getValue(index))
if annotationList == []:
continue
annotationDictionary[key].add(tuple(annotationList))
#annotationDictionary[frozenset(annotationList)].sort(lambda x,y: cmp(len(x), len(y)))
return annotationDictionary
def getSpeciesAnnotationStructure(parser):
model = parser.model
for species in model.getListOfSpecies():
name = species.getName()
speciesId = species.getId()
annotation = species.getAnnotation()
lista = libsbml.CVTermList()
libsbml.RDFAnnotationParser.parseRDFAnnotation(annotation,lista)
for idx in range(0,lista.getSize()):
for idx2 in range(0, lista.get(idx).getResources().getLength()):
resource = lista.get(idx).getResources().getValue(idx2)
qualifierType = lista.get(idx).getQualifierType()
qualifierDescription= bioqual[lista.get(idx).getBiologicalQualifierType()] if qualifierType \
else modqual[lista.get(idx).getModelQualifierType()]
#resource = resolveAnnotation(resource)
def getEquivalence(species,rdf_database):
'''
*species* is the species whose equivalence we will go and search
This method will search through the RDF database and look if param 'species'
is equal to any other element in the species database
'''
for element in rdf_database:
if species in rdf_database[element]:
if rdf_database[element].index(species) == 0:
return []
#return [x for x in rdf_database[element] if x != species]
#well only return the first one by default
return [rdf_database[element][0]]
return []
if __name__ == "__main__":
reader = libsbml.SBMLReader()
#BIOMD0000000272
document = reader.readSBMLFromFile('XMLExamples/curated/BIOMD0000000219.xml')
#document = reader.readSBMLFromFile('XMLExamples/simple4.xml')
model = document.getModel()
parser = SBML2BNGL(model)
annotationDictionary = getAnnotations(parser)
print annotationDictionary
#print getEquivalence('SAv_EpoR',annotationDictionary)
#print annotation
#print rules
| 37.790123 | 107 | 0.662202 |
"""
Created on Fri Apr 27 14:45:24 2012
@author: proto
"""
'''
this method classifies reactants according to the rdf information, and gives
us information on which reactants are the same, and how do they differ
(compartment etc)
'''
from sbml2bngl import SBML2BNGL
import libsbml
import collections
def getAnnotations(parser,stringKey=None):
annotation = parser.getSpeciesAnnotation()
annotationDictionary = collections.defaultdict(set)
for key,value in annotation.items():
annotationList = []
if annotation[key] != None:
for element in annotation[key]:
for index in range(0,element.getNumAttributes()):
if not stringKey or stringKey in element.getValue(index):
annotationList.append(element.getValue(index))
if annotationList == []:
continue
annotationDictionary[key].add(tuple(annotationList))
return annotationDictionary
def getSpeciesAnnotationStructure(parser):
model = parser.model
for species in model.getListOfSpecies():
name = species.getName()
speciesId = species.getId()
annotation = species.getAnnotation()
lista = libsbml.CVTermList()
libsbml.RDFAnnotationParser.parseRDFAnnotation(annotation,lista)
for idx in range(0,lista.getSize()):
for idx2 in range(0, lista.get(idx).getResources().getLength()):
resource = lista.get(idx).getResources().getValue(idx2)
qualifierType = lista.get(idx).getQualifierType()
qualifierDescription= bioqual[lista.get(idx).getBiologicalQualifierType()] if qualifierType \
else modqual[lista.get(idx).getModelQualifierType()]
def getEquivalence(species,rdf_database):
'''
*species* is the species whose equivalence we will go and search
This method will search through the RDF database and look if param 'species'
is equal to any other element in the species database
'''
for element in rdf_database:
if species in rdf_database[element]:
if rdf_database[element].index(species) == 0:
return []
return [rdf_database[element][0]]
return []
if __name__ == "__main__":
reader = libsbml.SBMLReader()
document = reader.readSBMLFromFile('XMLExamples/curated/BIOMD0000000219.xml')
model = document.getModel()
parser = SBML2BNGL(model)
annotationDictionary = getAnnotations(parser)
print annotationDictionary
| false | true |
f72c197e8fe4e17b1d25cf875d15b358ebf7e019 | 3,413 | py | Python | Dataproc/synth.py | Firehed/google-cloud-php | 5c49ed7a36c276fc59a9eaf9a03db4cd522b6932 | [
"Apache-2.0"
] | 1 | 2019-11-17T06:56:43.000Z | 2019-11-17T06:56:43.000Z | Dataproc/synth.py | Firehed/google-cloud-php | 5c49ed7a36c276fc59a9eaf9a03db4cd522b6932 | [
"Apache-2.0"
] | null | null | null | Dataproc/synth.py | Firehed/google-cloud-php | 5c49ed7a36c276fc59a9eaf9a03db4cd522b6932 | [
"Apache-2.0"
] | 1 | 2019-10-16T03:38:59.000Z | 2019-10-16T03:38:59.000Z | # Copyright 2018 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
#
# 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.
"""This script is used to synthesize generated parts of this library."""
import os
import synthtool as s
import synthtool.gcp as gcp
import logging
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICGenerator()
common = gcp.CommonTemplates()
for version in ['V1', 'V1beta2']:
lower_version = version.lower()
library = gapic.php_library(
service='dataproc',
version=lower_version,
artman_output_name=f'google-cloud-dataproc-{lower_version}')
# copy all src including partial veneer classes
s.move(library / 'src')
# copy proto files to src also
s.move(library / 'proto/src/Google/Cloud/Dataproc', 'src/')
s.move(library / 'tests/')
# copy GPBMetadata file to metadata
s.move(library / 'proto/src/GPBMetadata/Google/Cloud/Dataproc', 'metadata/')
# Use new namespaces
s.replace(
f'src/{version}/Gapic/JobControllerGapicClient.php',
r'ListJobsRequest_JobStateMatcher',
r'ListJobsRequest\\JobStateMatcher')
# document and utilize apiEndpoint instead of serviceAddress
s.replace(
"**/Gapic/*GapicClient.php",
r"'serviceAddress' =>",
r"'apiEndpoint' =>")
s.replace(
"**/Gapic/*GapicClient.php",
r"@type string \$serviceAddress\n\s+\*\s+The address",
r"""@type string $serviceAddress
* **Deprecated**. This option will be removed in a future major release. Please
* utilize the `$apiEndpoint` option instead.
* @type string $apiEndpoint
* The address""")
s.replace(
"**/Gapic/*GapicClient.php",
r"\$transportConfig, and any \$serviceAddress",
r"$transportConfig, and any `$apiEndpoint`")
# prevent proto messages from being marked final
s.replace(
"src/V*/**/*.php",
r"final class",
r"class")
# Replace "Unwrapped" with "Value" for method names.
s.replace(
"src/V*/**/*.php",
r"public function ([s|g]\w{3,})Unwrapped",
r"public function \1Value"
)
# fix year
for client in ['ClusterController', 'JobController']:
s.replace(
f'**/V1/Gapic/{client}GapicClient.php',
r'Copyright \d{4}',
'Copyright 2017')
s.replace(
f'**/V1/{client}Client.php',
r'Copyright \d{4}',
'Copyright 2017')
s.replace(
'**/V1beta2/Gapic/*GapicClient.php',
r'Copyright \d{4}',
r'Copyright 2019')
s.replace(
'**/V1beta2/*Client.php',
r'Copyright \d{4}',
r'Copyright 2019')
s.replace(
'**/V1/Gapic/WorkflowTemplateServiceGapicClient.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'**/V1/WorkflowTemplateServiceClient.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'tests/**/V1/*Test.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'tests/**/V1beta2/*Test.php',
r'Copyright \d{4}',
'Copyright 2019')
| 29.17094 | 94 | 0.658951 |
import os
import synthtool as s
import synthtool.gcp as gcp
import logging
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICGenerator()
common = gcp.CommonTemplates()
for version in ['V1', 'V1beta2']:
lower_version = version.lower()
library = gapic.php_library(
service='dataproc',
version=lower_version,
artman_output_name=f'google-cloud-dataproc-{lower_version}')
s.move(library / 'src')
s.move(library / 'proto/src/Google/Cloud/Dataproc', 'src/')
s.move(library / 'tests/')
s.move(library / 'proto/src/GPBMetadata/Google/Cloud/Dataproc', 'metadata/')
s.replace(
f'src/{version}/Gapic/JobControllerGapicClient.php',
r'ListJobsRequest_JobStateMatcher',
r'ListJobsRequest\\JobStateMatcher')
s.replace(
"**/Gapic/*GapicClient.php",
r"'serviceAddress' =>",
r"'apiEndpoint' =>")
s.replace(
"**/Gapic/*GapicClient.php",
r"@type string \$serviceAddress\n\s+\*\s+The address",
r"""@type string $serviceAddress
* **Deprecated**. This option will be removed in a future major release. Please
* utilize the `$apiEndpoint` option instead.
* @type string $apiEndpoint
* The address""")
s.replace(
"**/Gapic/*GapicClient.php",
r"\$transportConfig, and any \$serviceAddress",
r"$transportConfig, and any `$apiEndpoint`")
s.replace(
"src/V*/**/*.php",
r"final class",
r"class")
s.replace(
"src/V*/**/*.php",
r"public function ([s|g]\w{3,})Unwrapped",
r"public function \1Value"
)
for client in ['ClusterController', 'JobController']:
s.replace(
f'**/V1/Gapic/{client}GapicClient.php',
r'Copyright \d{4}',
'Copyright 2017')
s.replace(
f'**/V1/{client}Client.php',
r'Copyright \d{4}',
'Copyright 2017')
s.replace(
'**/V1beta2/Gapic/*GapicClient.php',
r'Copyright \d{4}',
r'Copyright 2019')
s.replace(
'**/V1beta2/*Client.php',
r'Copyright \d{4}',
r'Copyright 2019')
s.replace(
'**/V1/Gapic/WorkflowTemplateServiceGapicClient.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'**/V1/WorkflowTemplateServiceClient.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'tests/**/V1/*Test.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'tests/**/V1beta2/*Test.php',
r'Copyright \d{4}',
'Copyright 2019')
| true | true |
f72c198a930ed3f71634b2475161d1817b4821ff | 12,725 | py | Python | simulacionPlanificador.py | inakiuy/teoria-de-la-computacion | e9087e70622a72b8ddd44a3552f13c0e1794587d | [
"MIT"
] | null | null | null | simulacionPlanificador.py | inakiuy/teoria-de-la-computacion | e9087e70622a72b8ddd44a3552f13c0e1794587d | [
"MIT"
] | null | null | null | simulacionPlanificador.py | inakiuy/teoria-de-la-computacion | e9087e70622a72b8ddd44a3552f13c0e1794587d | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
from collections import deque
import random
SETS = 3 # Cantidad de sets generados
TASKS_CREATED = 10 # Cantidad de tareas creadas por cada set
MAX_SERVICETIME = 100 # Maximo Tiempo de Servicio de una tarea. 28800 = 8h
MAX_SERVICELIST_SIZE = 4 # Maxima canitad de particiones realizadas al tiempo de servicio
MAX_TIMEOUT = 150 # Maximo Tiempo de Timeout de una tarea
DIA_TRABAJO = 300 # Cuantos ciclos dura un dia de trabajo
MAX_TIME = 3000 # Cuantos ciclos dura la simulacion. SETS * TASKS_CREATED * MAX_SERVICETIME = 2880000
ALGO = "fcfs" # Algoritmo de planificacion FirstComeFirstServe
#ALGO = "sjf" # Algoritmo de planificacion ShortesJobFirst
INTERVALO_LOG = 1500 # Cada cuantos ciclos imprimir log.
class Tarea:
""" Clase tarea """
### Constructor
def __init__(self, pname, pserviceTime, ppriority, purgency, ptimeOut, ptaskType):
# Propiedades basicas
self.name = pname
self.serviceTime = pserviceTime
self.serviceList = Tarea.randomServiceList(pserviceTime)
self.priority = int(ppriority * purgency)
self.timeOut = ptimeOut
self.taskType = ptaskType
# Propiedades estadisticas
self.startTime = None
self.finishTime = None
self.waitingTime = 0
self.workDone = 0
self.waitingQueueArriveTime = None
self.serviceListCopy = self.serviceList.copy()
### Particiona de forma aleatoria un tiempo de servicio
### para simular tareas que necesitan espera
def randomServiceList(pserviceTime):
list_size = random.randrange(1,MAX_SERVICELIST_SIZE)
lista = deque(maxlen=list_size)
position = 0
# print(f'Tamanio lista: {list_size}')
for i in range(list_size - 1 ):
partition = random.randrange(position, pserviceTime)
# print(f'Loop: {i}, Posicion: {position}, Particion: {partition}, PserviceTime: {pserviceTime}')
time = partition - position
if (time != 0):
lista.append(time)
position = partition
lista.append(pserviceTime - position)
# print(f'Ver lista: {lista}')
return lista
### Generador de tareas aleatorias
def createRandomList(n_val, setNumber):
task_list = []
for n in range(n_val):
name = n + (TASKS_CREATED * setNumber)
serviceTime = random.randint(1,MAX_SERVICETIME)
priority = random.randint(0,5)
urgency = random.random() # random entre 0 y 1
timeout = random.randint(1,MAX_TIMEOUT) # Si no se ejecuta se da por no completada
tasktype = random.randrange(0,5) # Simulamos 5 tipos de tareas
task = Tarea(name, serviceTime, priority, urgency, timeout, tasktype)
task_list.append(task)
#print("Set de tareas generado correctamente")
return task_list
### Imprime estadisticas de forma legible
def prettyStats(self):
print(f'Tarea: {self.name}\n\tstart: {self.startTime}\n\tfinish: {self.finishTime}\n\twaiting: {self.waitingTime}\n\twork: {self.workDone}\n\tserviceList: {list(self.serviceListCopy)}')
### Imprime estadisticas crudas
def rawStats(self):
print(f'{self.name};{self.startTime};{self.finishTime};{self.waitingTime};{self.workDone};{list(self.serviceListCopy)}')
### Representacion de la tarea como string
def __repr__(self):
return f'\n{{name: {self.name}, time: {self.serviceTime}, serviceList: {list(self.serviceList)}, startTime: {self.startTime}, finishTime: {self.finishTime}, waitingTime: {self.waitingTime}, workDone: {self.workDone}, serviceListCopy: {list(self.serviceListCopy)}}}\n'
#return f'\n{{name: {self.name}, time: {self.serviceTime}, serviceList: {list(self.serviceList)}, priority: {self.priority}, timeout: {self.timeOut}, tasktype: {self.taskType}}}\n'
class Planificador:
""" Cola de tareas """
### Constructor
def __init__(self, ALGO):
self.algorithm = ALGO
self.planQueue = deque(maxlen=TASKS_CREATED * SETS)
self.waitingQueue = deque(maxlen=TASKS_CREATED * SETS)
self.finishedQueue = deque(maxlen=TASKS_CREATED * SETS)
### Poner una tarea en la cola de planificacion
def putTaskPlanQueue(self, task):
if (self.algorithm == "fcfs"):
# FCFS
self.fcfs(task)
elif (self.algorithm == "sjf"):
# SJF
self.sjf(task)
else:
raise Exception("Planificador no selecionado. Revise la constante ALGO")
# print(f'Tarea agregada: {task}')
### Entregar una tarea al usuario dede la cola de planificados
def getTaskPlanQueue(self):
return self.planQueue.popleft() if (self.planQueue) else None
### Poner una tarea en la cola de espera
def putTaskWaitingQueue(self, task, time):
task.waitingQueueArriveTime = time
self.waitingQueue.append(task)
return 0
### Eliminar una determinada tarea en la cola de espera
def removeTaskWaitingQueue(self, task):
self.waitingQueue.remove(task)
return 0
### Poner una tarea en la cola de finalizados
def putTaskFinishedQueue(self, task, time):
task.finishTime = time
self.finishedQueue.append(task)
return 0
### Imprimir todas las tareas en la cola
def printTasks(self):
print(f'Cola de tareas: {list(self.planQueue)}')
return 0
### Agregar tareas a la cola de planificacion
def addTasks(self, taskList, time):
for task in taskList:
task.startTime = time
self.putTaskPlanQueue(task)
return 0
### Algoritmo FCFS
def fcfs(self, task):
self.planQueue.append(task)
### Algoritmo SJF
def sjf(self, task):
serviceTime = task.serviceTime
queueList = list(self.planQueue)
i = 0
try:
while (queueList[i].serviceTime < serviceTime):
i += 1
self.planQueue.insert(i, task)
except:
self.planQueue.append(task)
# Replanificardor: Avanza el tiempo en 1 y las tareas que yas terminaron
# de esperar las mueve a la cola planQueue
def schedule(self, time):
#Necesaria por que no puedo modificar las colas mientras itero sobre ellas
tempList = []
# Si hay tareas esperando que ya cumplieron el tiempo de espera
# y que tienen ciclos de trabajo pendientes, pasarlas nuevamente
# a la cola de planificación
if (self.waitingQueue): # Si no esta vacia
for tarea in self.waitingQueue:
if (tarea.serviceList): # Si aun le quedan operaciones por hacer
timeWaited = time - tarea.waitingQueueArriveTime
timeToWait = tarea.serviceList[0]
if (timeWaited >= timeToWait):
tarea.serviceList.popleft()
if (tarea.serviceList): # Si le quedan operaciones
# Pasa a planificado
#print("Tiene operaciones, pasa a planificador")
tempList.append(tarea)
self.putTaskPlanQueue(tarea)
else:
# Pasa a finalizado
tempList.append(tarea)
#print("Ya no tiene operaciones, pasa a finalizado")
self.putTaskFinishedQueue(tarea, time)
else:
print('No debería estar aca')
# Elimino las tareas de la cola de espera
for tarea in tempList:
self.removeTaskWaitingQueue(tarea)
# A todas las tareas que están planificadas y no se avanzaron
# sumarle al waitingTime para estadisticas
if (self.planQueue):
for tarea in self.planQueue:
tarea.waitingTime += 1
### Imprimir estadisticas de la tareas
### Por omision imprime "pretty" legible para humanos
### poner raw en true devuelve lista separada por ";"
def printStatistics(self, raw):
print(f'\nCOLA TAREAS PLANIFICADAS')
if raw:
print(f'name;startTime;finishTime;waitingTime;workDone;serviceListCopy;')
if (self.planQueue):
for tarea in self.planQueue:
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
print(f'\nCOLA TAREAS ESPERANDO')
if raw:
print(f'name;startTime;finishTime;waitingTime;workDone;serviceListCopy;')
if (self.waitingQueue):
for tarea in self.waitingQueue:
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
print(f'\nCOLA TAREAS FINALIZADAS')
if raw:
print(f'name;startTime;finishTime;waitingTime;workDone;serviceListCopy;')
if (self.finishedQueue):
for tarea in self.finishedQueue:
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
class Persona:
""" Clase Persona que realiza trabajos """
# Constructor
def __init__(self, pname):
self.name = pname
self.task = None
# Realizar tarea
def work(self):
self.task.workDone += 1
def main():
""" Tests de planificación """
print(f'=== TESTS DE PLANIFICADOR {ALGO} ===')
print(f'Generamos {SETS} sets de pruebas')
setsTareas = deque()
for i in range(SETS):
setsTareas.append(Tarea.createRandomList(TASKS_CREATED, i))
planFCFS = Planificador(ALGO)
planFCFS.addTasks(setsTareas.popleft(), 0)
planFCFS.printTasks()
trabajador = Persona("Trabajador 1")
tarea = planFCFS.getTaskPlanQueue()
trabajador.task = tarea
workToBeDone = tarea.serviceList.popleft()
# SIMULACION DE TIEMPO
for time in range(MAX_TIME):
# Si paso 1 dia, agregamos mas tareas
if ( time != 0 and time % DIA_TRABAJO == 0 and setsTareas):
print(f'\n********************* NUEVO DIA: {time} *************************')
planFCFS.addTasks(setsTareas.popleft(), time)
# Imprimimos avance cada cierto intervalo
if ( time % INTERVALO_LOG == 0):
print(f'\n///////////////////////////////// Tiempo: {time} /////////////////////////////////')
print(f'Trabajador trabajando en: {trabajador.task}')
if (trabajador.task != None):
# Teniendo una tarea asignada
if ( tarea.workDone < workToBeDone ): # Si el trabajo realizado es menor al necesario, trabajar
trabajador.work()
elif (not tarea.serviceList): # Si en la lista de trabajo NO hay trabajo, pasa a cola de finalizado
trabajador.task = None
planFCFS.putTaskFinishedQueue(tarea, time)
else:
trabajador.task = None
planFCFS.putTaskWaitingQueue(tarea, time)
# Si no estamos trabajando en una tarea y aun quedan tareas
# en la cola de planQueue obtener una
if (trabajador.task == None and planFCFS.planQueue):
tarea = planFCFS.getTaskPlanQueue()
trabajador.task = tarea
workToBeDone = tarea.serviceList.popleft()
trabajador.work()
# Vemos el estado de las colas cada 100 tick del reloj
if ( time % INTERVALO_LOG == 0 ):
print(f'FinCiclo-PlanQ: {planFCFS.planQueue}\n-------------------------')
print(f'FinCiclo-WaitQ: {planFCFS.waitingQueue}\n-------------------------')
print(f'FinCiclo-FiniQ: {planFCFS.finishedQueue}\n-------------------------')
# Reprogramamos tareas
planFCFS.schedule(time)
print(f'\n--------------- FIN DEL TIEMPO SIMULADO ---------------')
print(f'FIN-PlanQ: {planFCFS.planQueue}\n-------------------------')
print(f'FIN-WaitQ: {planFCFS.waitingQueue}\n-------------------------')
print(f'FIN-FiniQ: {planFCFS.finishedQueue}\n-------------------------')
print(f'\n--------------- ESTADISTICAS PRETTY ---------------')
planFCFS.printStatistics(raw=False)
print(f'\n--------------- ESTADISTICAS RAW ---------------')
planFCFS.printStatistics(raw=True)
if __name__ == "__main__":
""" This is executed when run from the command line """
main() | 40.015723 | 275 | 0.595521 |
from collections import deque
import random
SETS = 3
TASKS_CREATED = 10
MAX_SERVICETIME = 100
MAX_SERVICELIST_SIZE = 4
MAX_TIMEOUT = 150
DIA_TRABAJO = 300
MAX_TIME = 3000
ALGO = "fcfs"
me, pserviceTime, ppriority, purgency, ptimeOut, ptaskType):
self.name = pname
self.serviceTime = pserviceTime
self.serviceList = Tarea.randomServiceList(pserviceTime)
self.priority = int(ppriority * purgency)
self.timeOut = ptimeOut
self.taskType = ptaskType
self.startTime = None
self.finishTime = None
self.waitingTime = 0
self.workDone = 0
self.waitingQueueArriveTime = None
self.serviceListCopy = self.serviceList.copy()
for i in range(list_size - 1 ):
partition = random.randrange(position, pserviceTime)
time = partition - position
if (time != 0):
lista.append(time)
position = partition
lista.append(pserviceTime - position)
return lista
[]
for n in range(n_val):
name = n + (TASKS_CREATED * setNumber)
serviceTime = random.randint(1,MAX_SERVICETIME)
priority = random.randint(0,5)
urgency = random.random()
timeout = random.randint(1,MAX_TIMEOUT)
tasktype = random.randrange(0,5)
task = Tarea(name, serviceTime, priority, urgency, timeout, tasktype)
task_list.append(task)
return task_list
startTime}\n\tfinish: {self.finishTime}\n\twaiting: {self.waitingTime}\n\twork: {self.workDone}\n\tserviceList: {list(self.serviceListCopy)}')
startTime};{self.finishTime};{self.waitingTime};{self.workDone};{list(self.serviceListCopy)}')
iceTime}, serviceList: {list(self.serviceList)}, startTime: {self.startTime}, finishTime: {self.finishTime}, waitingTime: {self.waitingTime}, workDone: {self.workDone}, serviceListCopy: {list(self.serviceListCopy)}}}\n'
class Planificador:
O):
self.algorithm = ALGO
self.planQueue = deque(maxlen=TASKS_CREATED * SETS)
self.waitingQueue = deque(maxlen=TASKS_CREATED * SETS)
self.finishedQueue = deque(maxlen=TASKS_CREATED * SETS)
self.fcfs(task)
elif (self.algorithm == "sjf"):
self.sjf(task)
else:
raise Exception("Planificador no selecionado. Revise la constante ALGO")
self.waitingQueue.append(task)
return 0
self.finishedQueue.append(task)
return 0
ue)}')
return 0
.startTime = time
self.putTaskPlanQueue(task)
return 0
self.planQueue.append(task)
serviceTime = task.serviceTime
queueList = list(self.planQueue)
i = 0
try:
while (queueList[i].serviceTime < serviceTime):
i += 1
self.planQueue.insert(i, task)
except:
self.planQueue.append(task)
def schedule(self, time):
tempList = []
if (self.waitingQueue):
for tarea in self.waitingQueue:
if (tarea.serviceList):
timeWaited = time - tarea.waitingQueueArriveTime
timeToWait = tarea.serviceList[0]
if (timeWaited >= timeToWait):
tarea.serviceList.popleft()
if (tarea.serviceList):
tempList.append(tarea)
self.putTaskPlanQueue(tarea)
else:
tempList.append(tarea)
self.putTaskFinishedQueue(tarea, time)
else:
print('No debería estar aca')
for tarea in tempList:
self.removeTaskWaitingQueue(tarea)
if (self.planQueue):
for tarea in self.planQueue:
tarea.waitingTime += 1
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
print(f'\nCOLA TAREAS ESPERANDO')
if raw:
print(f'name;startTime;finishTime;waitingTime;workDone;serviceListCopy;')
if (self.waitingQueue):
for tarea in self.waitingQueue:
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
print(f'\nCOLA TAREAS FINALIZADAS')
if raw:
print(f'name;startTime;finishTime;waitingTime;workDone;serviceListCopy;')
if (self.finishedQueue):
for tarea in self.finishedQueue:
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
class Persona:
def __init__(self, pname):
self.name = pname
self.task = None
def work(self):
self.task.workDone += 1
def main():
print(f'=== TESTS DE PLANIFICADOR {ALGO} ===')
print(f'Generamos {SETS} sets de pruebas')
setsTareas = deque()
for i in range(SETS):
setsTareas.append(Tarea.createRandomList(TASKS_CREATED, i))
planFCFS = Planificador(ALGO)
planFCFS.addTasks(setsTareas.popleft(), 0)
planFCFS.printTasks()
trabajador = Persona("Trabajador 1")
tarea = planFCFS.getTaskPlanQueue()
trabajador.task = tarea
workToBeDone = tarea.serviceList.popleft()
for time in range(MAX_TIME):
if ( time != 0 and time % DIA_TRABAJO == 0 and setsTareas):
print(f'\n********************* NUEVO DIA: {time} *************************')
planFCFS.addTasks(setsTareas.popleft(), time)
if ( time % INTERVALO_LOG == 0):
print(f'\n///////////////////////////////// Tiempo: {time} /////////////////////////////////')
print(f'Trabajador trabajando en: {trabajador.task}')
if (trabajador.task != None):
if ( tarea.workDone < workToBeDone ):
trabajador.work()
elif (not tarea.serviceList):
trabajador.task = None
planFCFS.putTaskFinishedQueue(tarea, time)
else:
trabajador.task = None
planFCFS.putTaskWaitingQueue(tarea, time)
if (trabajador.task == None and planFCFS.planQueue):
tarea = planFCFS.getTaskPlanQueue()
trabajador.task = tarea
workToBeDone = tarea.serviceList.popleft()
trabajador.work()
if ( time % INTERVALO_LOG == 0 ):
print(f'FinCiclo-PlanQ: {planFCFS.planQueue}\n-------------------------')
print(f'FinCiclo-WaitQ: {planFCFS.waitingQueue}\n-------------------------')
print(f'FinCiclo-FiniQ: {planFCFS.finishedQueue}\n-------------------------')
planFCFS.schedule(time)
print(f'\n--------------- FIN DEL TIEMPO SIMULADO ---------------')
print(f'FIN-PlanQ: {planFCFS.planQueue}\n-------------------------')
print(f'FIN-WaitQ: {planFCFS.waitingQueue}\n-------------------------')
print(f'FIN-FiniQ: {planFCFS.finishedQueue}\n-------------------------')
print(f'\n--------------- ESTADISTICAS PRETTY ---------------')
planFCFS.printStatistics(raw=False)
print(f'\n--------------- ESTADISTICAS RAW ---------------')
planFCFS.printStatistics(raw=True)
if __name__ == "__main__":
main() | true | true |
f72c19b9cb3d05c83471ebe6d0f7ab647fcf3c80 | 5,478 | py | Python | saas/api/backend.py | markcstansberry/djaodjin-saas | 0749dac36c3b039334fe9f115d92b3167eea03d6 | [
"BSD-2-Clause"
] | null | null | null | saas/api/backend.py | markcstansberry/djaodjin-saas | 0749dac36c3b039334fe9f115d92b3167eea03d6 | [
"BSD-2-Clause"
] | 4 | 2021-04-08T21:56:58.000Z | 2022-02-10T13:26:56.000Z | saas/api/backend.py | markcstansberry/djaodjin-saas | 0749dac36c3b039334fe9f115d92b3167eea03d6 | [
"BSD-2-Clause"
] | null | null | null | # Copyright (c) 2019, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pylint:disable=useless-super-delegation
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.generics import (RetrieveAPIView,
RetrieveUpdateDestroyAPIView)
from rest_framework.response import Response
from ..backends import ProcessorError
from ..docs import swagger_auto_schema
from ..mixins import OrganizationMixin
from .serializers import (BankSerializer, CardSerializer,
CardTokenSerializer)
#pylint: disable=no-init
class RetrieveBankAPIView(OrganizationMixin, RetrieveAPIView):
"""
Retrieves a payout account
Pass through that calls the processor API to retrieve some details about
the deposit account associated to a provider (if that information is
available through the :doc:`payment processor backend<backends>` API).
This API does not trigger payment of a subscriber to a provider. Checkout
of a subscription cart is done either through the
:ref:`HTML page<pages_cart>` or :ref:`API end point<api_checkout>`.
**Tags**: billing
**Examples**
.. code-block:: http
GET /api/billing/cowork/bank/ HTTP/1.1
responds
.. code-block:: json
{
"bank_name": "Stripe Test Bank",
"last4": "***-htrTZ",
"balance_amount": 0,
"balance_unit": "usd"
}
"""
serializer_class = BankSerializer
def retrieve(self, request, *args, **kwargs):
#pylint: disable=unused-argument
return Response(
self.organization.retrieve_bank())
class PaymentMethodDetailAPIView(OrganizationMixin,
RetrieveUpdateDestroyAPIView):
"""
Retrieves a payment method
Pass through to the processor to retrieve some details about
the payment method (ex: credit card) associated to a subscriber.
**Tags**: billing
**Examples**
.. code-block:: http
GET /api/billing/cowork/card/ HTTP/1.1
responds
.. code-block:: json
{
"last4": "1234",
"exp_date": "12/2019"
}
"""
serializer_class = CardSerializer
def delete(self, request, *args, **kwargs):
"""
Deletes a payment method
Pass through to the processor to remove the payment method (ex: credit
card) associated to a subscriber.
**Tags**: billing
**Examples**
.. code-block:: http
DELETE /api/billing/cowork/card/ HTTP/1.1
"""
return super(PaymentMethodDetailAPIView, self).delete(
request, *args, **kwargs)
@swagger_auto_schema(request_body=CardTokenSerializer)
def put(self, request, *args, **kwargs):
"""
Updates a payment method
Pass through to the processor to update some details about
the payment method (ex: credit card) associated to a subscriber.
**Tags**: billing
**Examples**
.. code-block:: http
PUT /api/billing/cowork/card/ HTTP/1.1
.. code-block:: json
{
"token": "xyz"
}
responds
.. code-block:: json
{
"last4": "1234",
"exp_date": "12/2019"
}
"""
return super(PaymentMethodDetailAPIView, self).put(
request, *args, **kwargs)
def destroy(self, request, *args, **kwargs):
self.organization.delete_card()
return Response(status=status.HTTP_204_NO_CONTENT)
def retrieve(self, request, *args, **kwargs):
#pylint: disable=unused-argument
return Response(self.organization.retrieve_card())
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
serializer = CardTokenSerializer(data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
token = serializer.validated_data['token']
try:
self.organization.update_card(token, self.request.user)
except ProcessorError as err:
raise ValidationError(err)
return self.retrieve(request, *args, **kwargs)
| 30.949153 | 78 | 0.667579 |
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.generics import (RetrieveAPIView,
RetrieveUpdateDestroyAPIView)
from rest_framework.response import Response
from ..backends import ProcessorError
from ..docs import swagger_auto_schema
from ..mixins import OrganizationMixin
from .serializers import (BankSerializer, CardSerializer,
CardTokenSerializer)
class RetrieveBankAPIView(OrganizationMixin, RetrieveAPIView):
serializer_class = BankSerializer
def retrieve(self, request, *args, **kwargs):
return Response(
self.organization.retrieve_bank())
class PaymentMethodDetailAPIView(OrganizationMixin,
RetrieveUpdateDestroyAPIView):
serializer_class = CardSerializer
def delete(self, request, *args, **kwargs):
return super(PaymentMethodDetailAPIView, self).delete(
request, *args, **kwargs)
@swagger_auto_schema(request_body=CardTokenSerializer)
def put(self, request, *args, **kwargs):
return super(PaymentMethodDetailAPIView, self).put(
request, *args, **kwargs)
def destroy(self, request, *args, **kwargs):
self.organization.delete_card()
return Response(status=status.HTTP_204_NO_CONTENT)
def retrieve(self, request, *args, **kwargs):
return Response(self.organization.retrieve_card())
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
serializer = CardTokenSerializer(data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
token = serializer.validated_data['token']
try:
self.organization.update_card(token, self.request.user)
except ProcessorError as err:
raise ValidationError(err)
return self.retrieve(request, *args, **kwargs)
| true | true |
f72c1a54af7f21cf6b27146291cd2fe43fcaa17f | 11,489 | py | Python | src/maggma/api/query_operator.py | wuxiaohua1011/maggma | b7a059b2d12d9b96aa2092c40eb41f121c0a598b | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/maggma/api/query_operator.py | wuxiaohua1011/maggma | b7a059b2d12d9b96aa2092c40eb41f121c0a598b | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/maggma/api/query_operator.py | wuxiaohua1011/maggma | b7a059b2d12d9b96aa2092c40eb41f121c0a598b | [
"BSD-3-Clause-LBNL"
] | null | null | null | from typing import List, Dict, Optional, Any, Mapping
from pydantic import BaseModel
from fastapi import Query
from monty.json import MSONable
from maggma.core import Store
from maggma.api.util import STORE_PARAMS, dynamic_import
from pydantic.fields import ModelField
import inspect
import warnings
class QueryOperator(MSONable):
"""
Base Query Operator class for defining powerfull query language
in the Materials API
"""
def query(self) -> STORE_PARAMS:
"""
The query function that does the work for this query operator
"""
raise NotImplementedError("Query operators must implement query")
def meta(self, store: Store, query: Dict) -> Dict:
"""
Returns meta data to return with the Response
Args:
store: the Maggma Store that the resource uses
query: the query being executed in this API call
"""
return {}
def post_process(self, doc: Dict) -> Dict:
"""
An optional post-processing function for the data
"""
return doc
class PaginationQuery(QueryOperator):
"""Query opertators to provides Pagination in the Materials API"""
def __init__(
self, default_skip: int = 0, default_limit: int = 10, max_limit: int = 100
):
"""
Args:
default_skip: the default number of documents to skip
default_limit: the default number of documents to return
max_limit: max number of documents to return
"""
self.default_skip = default_skip
self.default_limit = default_limit
self.max_limit = max_limit
def query(
skip: int = Query(
default_skip, description="Number of entries to skip in the search"
),
limit: int = Query(
default_limit,
description="Max number of entries to return in a single query."
f" Limited to {max_limit}",
),
) -> STORE_PARAMS:
"""
Pagination parameters for the API Endpoint
"""
if limit > max_limit:
raise Exception(
"Requested more data per query than allowed by this endpoint."
f"The max limit is {max_limit} entries"
)
return {"skip": skip, "limit": limit}
self.query = query # type: ignore
def meta(self, store: Store, query: Dict) -> Dict:
"""
Metadata for the pagination params
"""
return {"max_limit": self.max_limit}
class SparseFieldsQuery(QueryOperator):
def __init__(self, model: BaseModel, default_fields: Optional[List[str]] = None):
"""
Args:
model: PyDantic Model that represents the underlying data source
default_fields: default fields to return in the API response if no fields are explicitly requested
"""
self.model = model
model_fields = list(self.model.__fields__.keys())
self.default_fields = (
model_fields if default_fields is None else list(default_fields)
)
assert set(self.default_fields).issubset(
model_fields
), "default projection contains some fields that are not in the model fields"
default_fields_string = ",".join(self.default_fields) # type: ignore
def query(
fields: str = Query(
default_fields_string,
description=f"Fields to project from {model.__name__} " # type: ignore
f"as a list of comma seperated strings",
),
all_fields: bool = Query(False, description="Include all fields."),
) -> STORE_PARAMS:
"""
Projection parameters for the API Endpoint
"""
projection_fields: List[str] = [s.strip() for s in fields.split(",")]
# need to strip to avoid input such as "name, weight" to be parsed into ["name", " weight"]
# we need ["name", "weight"]
if all_fields:
projection_fields = model_fields
return {"properties": projection_fields}
self.query = query # type: ignore
"""
Factory function to generate a dependency for sparse field sets in FastAPI
"""
def meta(self, store: Store, query: Dict) -> Dict:
"""
Returns metadata for the Sparse field set
"""
return {"default_fields": self.default_fields}
def as_dict(self) -> Dict:
"""
Special as_dict implemented to convert pydantic models into strings
"""
d = super().as_dict() # Ensures sub-classes serialize correctly
d["model"] = f"{self.model.__module__}.{self.model.__name__}" # type: ignore
return d
@classmethod
def from_dict(cls, d):
"""
Special from_dict to autoload the pydantic model from the location string
"""
model = d.get("model")
if isinstance(model, str):
module_path = ".".join(model.split(".")[:-1])
class_name = model.split(".")[-1]
model = dynamic_import(module_path, class_name)
assert issubclass(
model, BaseModel
), "The resource model has to be a PyDantic Model"
d["model"] = model
cls(**d)
class DefaultDynamicQuery(QueryOperator):
def __init__(
self, model: BaseModel, additional_signature_fields: Mapping[str, List] = None,
):
"""
This function will take query, parse it, and output the mongo criteria.
About the query:
The format of the input query will come from two sources: the data model (which we will sometimes refer to as
default values, and the additional paremeters that users can choose to pass in)
additional_signature_field must be int the shape of NAME_OF_THE_QUERY -> [DEFAULT_VALUE, QUERY]
where QUERY is a FastAPI params.Query object
About how does this script parse the query:
it will first generate default queries from input data model
Then it will merge with the optional additional_signature_fields
About mongo criteria output:
current implementation only supports 6 operations, namely equal, not equal, less than, greater than, in,
and not in. Therefore, the criteria output will be also limited to those operations.
Args:
model: PyDantic Model to base the query language on
additional_signature_fields: mapping of NAME_OF_THE_FIELD -> [DEFAULT_VALUE, QUERY]
"""
self.model = model
default_mapping = {
"eq": "$eq",
"not_eq": "$ne",
"lt": "$lt",
"gt": "$gt",
"in": "$in",
"not_in": "$nin",
}
mapping: dict = default_mapping
self.additional_signature_fields: Mapping[
str, List
] = dict() if additional_signature_fields is None else additional_signature_fields
# construct fields
# find all fields in data_object
all_fields: Dict[str, ModelField] = model.__fields__
# turn fields into operators, also do type checking
params = self.fields_to_operator(all_fields)
# combine with additional_fields
# user's input always have higher priority than the the default data model's
params.update(self.additional_signature_fields)
def query(**kwargs) -> STORE_PARAMS:
crit = dict()
for k, v in kwargs.items():
if v is not None:
if "_" not in k:
k = k + "_eq"
name, operator = k.split("_", 1)
try:
crit[name] = {mapping[operator]: v}
except KeyError:
raise KeyError(
f"Cannot find key {k} in current query to database mapping"
)
return {"criteria": crit}
# building the signatures for FastAPI Swagger UI
signatures: List[Any] = []
signatures.extend(
inspect.Parameter(
param,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
default=query[1],
annotation=query[0],
)
for param, query in params.items()
)
setattr(query, "__signature__", inspect.Signature(signatures))
self.query = query # type: ignore
def fields_to_operator(self, all_fields: Dict[str, ModelField]) -> Dict[str, list]:
"""
Getting a list of tuple of fields
turn them into a mapping of
FIELD_[operator] -> query
Args:
all_fields: dictionary of str -> ModelField
Returns:
a dictionary of FIELD_[operator] -> query
"""
params = dict()
for name, model_field in all_fields.items():
if model_field.type_ in [str, int, float]:
t: Any = model_field.type_
name = model_field.name
params[f"{name}"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is equal to another",
),
] # supporting both with and with out explicit _eq
params[f"{name}_eq"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is equal to another",
),
]
params[f"{name}_not_eq"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is not equal to another",
),
]
params[f"{name}_in"] = [
List[t],
Query(
default=model_field.default,
description=f"Querying if item is in {model_field.name}",
),
]
params[f"{name}_not_in"] = [
List[t],
Query(
default=model_field.default,
description=f"Querying if item is not in {model_field.name} ",
),
]
if model_field.type_ == int or model_field == float:
params[f"{name}_lt"] = [
model_field.type_,
Query(
model_field.default,
description=f"Querying if {model_field.name} is less than to another",
),
]
params[f"{name}_gt"] = [
model_field.type_,
Query(
model_field.default,
description=f"Querying if {model_field.name} is greater than to another",
),
]
else:
warnings.warn(
f"Field name {name} with {model_field.type_} not implemented"
)
return params
| 35.242331 | 117 | 0.542606 | from typing import List, Dict, Optional, Any, Mapping
from pydantic import BaseModel
from fastapi import Query
from monty.json import MSONable
from maggma.core import Store
from maggma.api.util import STORE_PARAMS, dynamic_import
from pydantic.fields import ModelField
import inspect
import warnings
class QueryOperator(MSONable):
def query(self) -> STORE_PARAMS:
raise NotImplementedError("Query operators must implement query")
def meta(self, store: Store, query: Dict) -> Dict:
return {}
def post_process(self, doc: Dict) -> Dict:
return doc
class PaginationQuery(QueryOperator):
def __init__(
self, default_skip: int = 0, default_limit: int = 10, max_limit: int = 100
):
self.default_skip = default_skip
self.default_limit = default_limit
self.max_limit = max_limit
def query(
skip: int = Query(
default_skip, description="Number of entries to skip in the search"
),
limit: int = Query(
default_limit,
description="Max number of entries to return in a single query."
f" Limited to {max_limit}",
),
) -> STORE_PARAMS:
if limit > max_limit:
raise Exception(
"Requested more data per query than allowed by this endpoint."
f"The max limit is {max_limit} entries"
)
return {"skip": skip, "limit": limit}
self.query = query
def meta(self, store: Store, query: Dict) -> Dict:
return {"max_limit": self.max_limit}
class SparseFieldsQuery(QueryOperator):
def __init__(self, model: BaseModel, default_fields: Optional[List[str]] = None):
self.model = model
model_fields = list(self.model.__fields__.keys())
self.default_fields = (
model_fields if default_fields is None else list(default_fields)
)
assert set(self.default_fields).issubset(
model_fields
), "default projection contains some fields that are not in the model fields"
default_fields_string = ",".join(self.default_fields)
def query(
fields: str = Query(
default_fields_string,
description=f"Fields to project from {model.__name__} "
f"as a list of comma seperated strings",
),
all_fields: bool = Query(False, description="Include all fields."),
) -> STORE_PARAMS:
projection_fields: List[str] = [s.strip() for s in fields.split(",")]
if all_fields:
projection_fields = model_fields
return {"properties": projection_fields}
self.query = query
def meta(self, store: Store, query: Dict) -> Dict:
return {"default_fields": self.default_fields}
def as_dict(self) -> Dict:
d = super().as_dict()
d["model"] = f"{self.model.__module__}.{self.model.__name__}"
return d
@classmethod
def from_dict(cls, d):
model = d.get("model")
if isinstance(model, str):
module_path = ".".join(model.split(".")[:-1])
class_name = model.split(".")[-1]
model = dynamic_import(module_path, class_name)
assert issubclass(
model, BaseModel
), "The resource model has to be a PyDantic Model"
d["model"] = model
cls(**d)
class DefaultDynamicQuery(QueryOperator):
def __init__(
self, model: BaseModel, additional_signature_fields: Mapping[str, List] = None,
):
self.model = model
default_mapping = {
"eq": "$eq",
"not_eq": "$ne",
"lt": "$lt",
"gt": "$gt",
"in": "$in",
"not_in": "$nin",
}
mapping: dict = default_mapping
self.additional_signature_fields: Mapping[
str, List
] = dict() if additional_signature_fields is None else additional_signature_fields
all_fields: Dict[str, ModelField] = model.__fields__
params = self.fields_to_operator(all_fields)
params.update(self.additional_signature_fields)
def query(**kwargs) -> STORE_PARAMS:
crit = dict()
for k, v in kwargs.items():
if v is not None:
if "_" not in k:
k = k + "_eq"
name, operator = k.split("_", 1)
try:
crit[name] = {mapping[operator]: v}
except KeyError:
raise KeyError(
f"Cannot find key {k} in current query to database mapping"
)
return {"criteria": crit}
signatures: List[Any] = []
signatures.extend(
inspect.Parameter(
param,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
default=query[1],
annotation=query[0],
)
for param, query in params.items()
)
setattr(query, "__signature__", inspect.Signature(signatures))
self.query = query
def fields_to_operator(self, all_fields: Dict[str, ModelField]) -> Dict[str, list]:
params = dict()
for name, model_field in all_fields.items():
if model_field.type_ in [str, int, float]:
t: Any = model_field.type_
name = model_field.name
params[f"{name}"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is equal to another",
),
]
params[f"{name}_eq"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is equal to another",
),
]
params[f"{name}_not_eq"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is not equal to another",
),
]
params[f"{name}_in"] = [
List[t],
Query(
default=model_field.default,
description=f"Querying if item is in {model_field.name}",
),
]
params[f"{name}_not_in"] = [
List[t],
Query(
default=model_field.default,
description=f"Querying if item is not in {model_field.name} ",
),
]
if model_field.type_ == int or model_field == float:
params[f"{name}_lt"] = [
model_field.type_,
Query(
model_field.default,
description=f"Querying if {model_field.name} is less than to another",
),
]
params[f"{name}_gt"] = [
model_field.type_,
Query(
model_field.default,
description=f"Querying if {model_field.name} is greater than to another",
),
]
else:
warnings.warn(
f"Field name {name} with {model_field.type_} not implemented"
)
return params
| true | true |
f72c1ab1de5a5c97a92db41310f7ac5f79e19552 | 4,330 | py | Python | bika/lims/browser/artemplate.py | hocinebendou/bika.gsoc | 85bc0c587de7f52073ae0e89bddbc77bf875f295 | [
"MIT"
] | null | null | null | bika/lims/browser/artemplate.py | hocinebendou/bika.gsoc | 85bc0c587de7f52073ae0e89bddbc77bf875f295 | [
"MIT"
] | null | null | null | bika/lims/browser/artemplate.py | hocinebendou/bika.gsoc | 85bc0c587de7f52073ae0e89bddbc77bf875f295 | [
"MIT"
] | null | null | null | from bika.lims.interfaces import IJSONReadExtender, IARTemplate
from zope.component import adapts
from zope.interface import implements
class JSONReadExtender(object):
"""- Place additional information about profile services
into the returned records.
Used in AR Add to prevent extra requests
"""
implements(IJSONReadExtender)
adapts(IARTemplate)
def __init__(self, context):
self.context = context
def render_template_partitions(self):
"""
Supplies a more detailed view of the Partitions for this
template. It's built to mimic the partitions that are stored in the
ar_add form state variable, so that when a partition is chosen, there
is no further translation necessary.
It combines the Analyses and Partitions AT schema field values.
For some fields (separate, minvol) there is no information, when partitions
are specified in the AR Template.
:return a list of dictionaries like this:
container
[]
container_titles
[]
preservation
[]
preservation_titles
[]
separate
false
minvol
"0.0000 m3 "
services
["2fdc040e05bb42ca8b52e41761fdb795", 6 more...]
service_titles
["Copper", "Iron", "Magnesium", 4 more...]
"""
Analyses = self.context.Schema()['Analyses'].get(self.context)
Parts = self.context.Schema()['Partitions'].get(self.context)
if not Parts:
# default value copied in from content/artemplate.py
Parts = [{'part_id': 'part-1',
'Container': '',
'Preservation': '',
'container_uid': '',
'preservation_uid': ''}]
parts = []
not_found = set()
for Part in Parts:
part = {
'part_id': Part.get("part_id", "part-1"),
'container_titles': Part.get("Container", ""),
'container': Part.get("container_uid", ""),
'preservation_titles': Part.get("Preservation", ""),
'preservation': Part.get("preservation_uid", ""),
'services': [],
'service_titles': [],
}
for analysis in Analyses:
uid = analysis['service_uid']
partiton = analysis['partition']
if partiton == part['part_id']:
part['services'].append(uid)
part['service_titles'].append(uid)
not_found.discard(analysis['service_uid'])
else:
if uid in part['services']:
part['services'].remove(uid)
if uid in part['service_titles']:
part['service_titles'].remove(uid)
not_found.add(analysis['service_uid'])
parts.append(part)
# all others go into the first part. Mostly this will be due to
# partition info not being defined?
for uid in not_found:
if uid not in part['services']:
parts[0]['services'].append(uid)
if uid not in part['service_titles']:
parts[0]['service_titles'].append(uid)
return parts
def __call__(self, request, data):
bsc = self.context.bika_setup_catalog
service_data = []
for item in self.context.getAnalyses():
service_uid = item['service_uid']
service = bsc(UID=service_uid)[0].getObject()
this_service = {'UID': service.UID(),
'Title': service.Title(),
'Keyword': service.getKeyword(),
'Price': service.getPrice(),
'VAT': service.getVAT(),
'PointOfCapture': service.getPointOfCapture(),
'CategoryTitle': service.getCategory().Title()}
service_data.append(this_service)
data['service_data'] = service_data
data['Partitions'] = self.render_template_partitions()
| 38.318584 | 83 | 0.526328 | from bika.lims.interfaces import IJSONReadExtender, IARTemplate
from zope.component import adapts
from zope.interface import implements
class JSONReadExtender(object):
implements(IJSONReadExtender)
adapts(IARTemplate)
def __init__(self, context):
self.context = context
def render_template_partitions(self):
Analyses = self.context.Schema()['Analyses'].get(self.context)
Parts = self.context.Schema()['Partitions'].get(self.context)
if not Parts:
Parts = [{'part_id': 'part-1',
'Container': '',
'Preservation': '',
'container_uid': '',
'preservation_uid': ''}]
parts = []
not_found = set()
for Part in Parts:
part = {
'part_id': Part.get("part_id", "part-1"),
'container_titles': Part.get("Container", ""),
'container': Part.get("container_uid", ""),
'preservation_titles': Part.get("Preservation", ""),
'preservation': Part.get("preservation_uid", ""),
'services': [],
'service_titles': [],
}
for analysis in Analyses:
uid = analysis['service_uid']
partiton = analysis['partition']
if partiton == part['part_id']:
part['services'].append(uid)
part['service_titles'].append(uid)
not_found.discard(analysis['service_uid'])
else:
if uid in part['services']:
part['services'].remove(uid)
if uid in part['service_titles']:
part['service_titles'].remove(uid)
not_found.add(analysis['service_uid'])
parts.append(part)
for uid in not_found:
if uid not in part['services']:
parts[0]['services'].append(uid)
if uid not in part['service_titles']:
parts[0]['service_titles'].append(uid)
return parts
def __call__(self, request, data):
bsc = self.context.bika_setup_catalog
service_data = []
for item in self.context.getAnalyses():
service_uid = item['service_uid']
service = bsc(UID=service_uid)[0].getObject()
this_service = {'UID': service.UID(),
'Title': service.Title(),
'Keyword': service.getKeyword(),
'Price': service.getPrice(),
'VAT': service.getVAT(),
'PointOfCapture': service.getPointOfCapture(),
'CategoryTitle': service.getCategory().Title()}
service_data.append(this_service)
data['service_data'] = service_data
data['Partitions'] = self.render_template_partitions()
| true | true |
f72c1c45126418c8a2273a6fc96e135d6bcf4da8 | 22,915 | py | Python | .infra/setup/playbooks/roles/ansible.kubernetes-modules/library/openshift_v1_group_list.py | cvicens/lab-knative | ef98aa111e566c6d33fd72c61f9c0d93a2c05b2f | [
"Apache-2.0"
] | null | null | null | .infra/setup/playbooks/roles/ansible.kubernetes-modules/library/openshift_v1_group_list.py | cvicens/lab-knative | ef98aa111e566c6d33fd72c61f9c0d93a2c05b2f | [
"Apache-2.0"
] | null | null | null | .infra/setup/playbooks/roles/ansible.kubernetes-modules/library/openshift_v1_group_list.py | cvicens/lab-knative | ef98aa111e566c6d33fd72c61f9c0d93a2c05b2f | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
from ansible.module_utils.openshift_common import OpenShiftAnsibleModule, OpenShiftAnsibleException
DOCUMENTATION = '''
module: openshift_v1_group_list
short_description: OpenShift GroupList
description:
- Retrieve a list of groups. List operations provide a snapshot read of the underlying
objects, returning a resource_version representing a consistent version of the listed
objects.
version_added: 2.3.0
author: OpenShift (@openshift)
options:
api_key:
description:
- Token used to connect to the API.
cert_file:
description:
- Path to a certificate used to authenticate with the API.
type: path
context:
description:
- The name of a context found in the Kubernetes config file.
debug:
description:
- Enable debug output from the OpenShift helper. Logging info is written to KubeObjHelper.log
default: false
type: bool
force:
description:
- If set to C(True), and I(state) is C(present), an existing object will updated,
and lists will be replaced, rather than merged.
default: false
type: bool
host:
description:
- Provide a URL for acessing the Kubernetes API.
key_file:
description:
- Path to a key file used to authenticate with the API.
type: path
kubeconfig:
description:
- Path to an existing Kubernetes config file. If not provided, and no other connection
options are provided, the openshift client will attempt to load the default
configuration file from I(~/.kube/config.json).
type: path
password:
description:
- Provide a password for connecting to the API. Use in conjunction with I(username).
resource_definition:
description:
- Provide the YAML definition for the object, bypassing any modules parameters
intended to define object attributes.
type: dict
src:
description:
- Provide a path to a file containing the YAML definition of the object. Mutually
exclusive with I(resource_definition).
type: path
ssl_ca_cert:
description:
- Path to a CA certificate used to authenticate with the API.
type: path
state:
description:
- Determines if an object should be created, patched, or deleted. When set to
C(present), the object will be created, if it does not exist, or patched, if
parameter values differ from the existing object's attributes, and deleted,
if set to C(absent). A patch operation results in merging lists and updating
dictionaries, with lists being merged into a unique set of values. If a list
contains a dictionary with a I(name) or I(type) attribute, a strategic merge
is performed, where individual elements with a matching I(name_) or I(type)
are merged. To force the replacement of lists, set the I(force) option to C(True).
default: present
choices:
- present
- absent
username:
description:
- Provide a username for connecting to the API.
verify_ssl:
description:
- Whether or not to verify the API server's SSL certificates.
type: bool
requirements:
- openshift == 0.3.3
'''
EXAMPLES = '''
'''
RETURN = '''
api_version:
type: string
description: Requested API version
group_list:
type: complex
returned: when I(state) = C(present)
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values.
type: str
items:
description:
- Items is the list of groups
type: list
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value,
and may reject unrecognized values.
type: str
kind:
description:
- Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to.
Cannot be updated. In CamelCase.
type: str
metadata:
description:
- Standard object's metadata.
type: complex
contains:
annotations:
description:
- Annotations is an unstructured key value map stored with a resource
that may be set by external tools to store and retrieve arbitrary
metadata. They are not queryable and should be preserved when modifying
objects.
type: complex
contains: str, str
cluster_name:
description:
- The name of the cluster which the object belongs to. This is used
to distinguish resources with same name and namespace in different
clusters. This field is not set anywhere right now and apiserver is
going to ignore it if set in create or update request.
type: str
creation_timestamp:
description:
- CreationTimestamp is a timestamp representing the server time when
this object was created. It is not guaranteed to be set in happens-before
order across separate operations. Clients may not set this value.
It is represented in RFC3339 form and is in UTC. Populated by the
system. Read-only. Null for lists.
type: complex
contains: {}
deletion_grace_period_seconds:
description:
- Number of seconds allowed for this object to gracefully terminate
before it will be removed from the system. Only set when deletionTimestamp
is also set. May only be shortened. Read-only.
type: int
deletion_timestamp:
description:
- DeletionTimestamp is RFC 3339 date and time at which this resource
will be deleted. This field is set by the server when a graceful deletion
is requested by the user, and is not directly settable by a client.
The resource is expected to be deleted (no longer visible from resource
lists, and not reachable by name) after the time in this field. Once
set, this value may not be unset or be set further into the future,
although it may be shortened or the resource may be deleted prior
to this time. For example, a user may request that a pod is deleted
in 30 seconds. The Kubelet will react by sending a graceful termination
signal to the containers in the pod. After that 30 seconds, the Kubelet
will send a hard termination signal (SIGKILL) to the container and
after cleanup, remove the pod from the API. In the presence of network
partitions, this object may still exist after this timestamp, until
an administrator or automated process can determine the resource is
fully terminated. If not set, graceful deletion of the object has
not been requested. Populated by the system when a graceful deletion
is requested. Read-only.
type: complex
contains: {}
finalizers:
description:
- Must be empty before the object is deleted from the registry. Each
entry is an identifier for the responsible component that will remove
the entry from the list. If the deletionTimestamp of the object is
non-nil, entries in this list can only be removed.
type: list
contains: str
generate_name:
description:
- GenerateName is an optional prefix, used by the server, to generate
a unique name ONLY IF the Name field has not been provided. If this
field is used, the name returned to the client will be different than
the name passed. This value will also be combined with a unique suffix.
The provided value has the same validation rules as the Name field,
and may be truncated by the length of the suffix required to make
the value unique on the server. If this field is specified and the
generated name exists, the server will NOT return a 409 - instead,
it will either return 201 Created or 500 with Reason ServerTimeout
indicating a unique name could not be found in the time allotted,
and the client should retry (optionally after the time indicated in
the Retry-After header). Applied only if Name is not specified.
type: str
generation:
description:
- A sequence number representing a specific generation of the desired
state. Populated by the system. Read-only.
type: int
initializers:
description:
- An initializer is a controller which enforces some system invariant
at object creation time. This field is a list of initializers that
have not yet acted on this object. If nil or empty, this object has
been completely initialized. Otherwise, the object is considered uninitialized
and is hidden (in list/watch and get calls) from clients that haven't
explicitly asked to observe uninitialized objects. When an object
is created, the system will populate this list with the current set
of initializers. Only privileged users may set or modify this list.
Once it is empty, it may not be modified further by any user.
type: complex
contains:
pending:
description:
- Pending is a list of initializers that must execute in order before
this object is visible. When the last pending initializer is removed,
and no failing result is set, the initializers struct will be
set to nil and the object is considered as initialized and visible
to all clients.
type: list
contains:
name:
description:
- name of the process that is responsible for initializing this
object.
type: str
result:
description:
- If result is set with the Failure field, the object will be persisted
to storage and then deleted, ensuring that other clients can observe
the deletion.
type: complex
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation
of an object. Servers should convert recognized schemas to
the latest internal value, and may reject unrecognized values.
type: str
code:
description:
- Suggested HTTP return code for this status, 0 if not set.
type: int
details:
description:
- Extended data associated with the reason. Each reason may
define its own extended details. This field is optional and
the data returned is not guaranteed to conform to any schema
except that defined by the reason type.
type: complex
contains:
causes:
description:
- The Causes array includes more details associated with
the StatusReason failure. Not all StatusReasons may provide
detailed causes.
type: list
contains:
field:
description:
- 'The field of the resource that has caused this error,
as named by its JSON serialization. May include dot
and postfix notation for nested attributes. Arrays
are zero-indexed. Fields may appear more than once
in an array of causes due to fields having multiple
errors. Optional. Examples: "name" - the field "name"
on the current resource "items[0].name" - the field
"name" on the first array entry in "items"'
type: str
message:
description:
- A human-readable description of the cause of the error.
This field may be presented as-is to a reader.
type: str
reason:
description:
- A machine-readable description of the cause of the
error. If this value is empty there is no information
available.
type: str
group:
description:
- The group attribute of the resource associated with the
status StatusReason.
type: str
kind:
description:
- The kind attribute of the resource associated with the
status StatusReason. On some operations may differ from
the requested resource Kind.
type: str
name:
description:
- The name attribute of the resource associated with the
status StatusReason (when there is a single name which
can be described).
type: str
retry_after_seconds:
description:
- If specified, the time in seconds before the operation
should be retried.
type: int
uid:
description:
- UID of the resource. (when there is a single resource
which can be described).
type: str
kind:
description:
- Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint
the client submits requests to. Cannot be updated. In CamelCase.
type: str
message:
description:
- A human-readable description of the status of this operation.
type: str
metadata:
description:
- Standard list metadata.
type: complex
contains:
resource_version:
description:
- String that identifies the server's internal version of
this object that can be used by clients to determine when
objects have changed. Value must be treated as opaque
by clients and passed unmodified back to the server. Populated
by the system. Read-only.
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated
by the system. Read-only.
type: str
reason:
description:
- A machine-readable description of why this operation is in
the "Failure" status. If this value is empty there is no information
available. A Reason clarifies an HTTP status code but does
not override it.
type: str
status:
description:
- 'Status of the operation. One of: "Success" or "Failure".'
type: str
labels:
description:
- Map of string keys and values that can be used to organize and categorize
(scope and select) objects. May match selectors of replication controllers
and services.
type: complex
contains: str, str
name:
description:
- Name must be unique within a namespace. Is required when creating
resources, although some resources may allow a client to request the
generation of an appropriate name automatically. Name is primarily
intended for creation idempotence and configuration definition. Cannot
be updated.
type: str
namespace:
description:
- Namespace defines the space within each name must be unique. An empty
namespace is equivalent to the "default" namespace, but "default"
is the canonical representation. Not all objects are required to be
scoped to a namespace - the value of this field for those objects
will be empty. Must be a DNS_LABEL. Cannot be updated.
type: str
owner_references:
description:
- List of objects depended by this object. If ALL objects in the list
have been deleted, this object will be garbage collected. If this
object is managed by a controller, then an entry in this list will
point to this controller, with the controller field set to true. There
cannot be more than one managing controller.
type: list
contains:
api_version:
description:
- API version of the referent.
type: str
block_owner_deletion:
description:
- If true, AND if the owner has the "foregroundDeletion" finalizer,
then the owner cannot be deleted from the key-value store until
this reference is removed. Defaults to false. To set this field,
a user needs "delete" permission of the owner, otherwise 422 (Unprocessable
Entity) will be returned.
type: bool
controller:
description:
- If true, this reference points to the managing controller.
type: bool
kind:
description:
- Kind of the referent.
type: str
name:
description:
- Name of the referent.
type: str
uid:
description:
- UID of the referent.
type: str
resource_version:
description:
- An opaque value that represents the internal version of this object
that can be used by clients to determine when objects have changed.
May be used for optimistic concurrency, change detection, and the
watch operation on a resource or set of resources. Clients must treat
these values as opaque and passed unmodified back to the server. They
may only be valid for a particular resource or set of resources. Populated
by the system. Read-only. Value must be treated as opaque by clients
and .
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated by the system.
Read-only.
type: str
uid:
description:
- UID is the unique in time and space value for this object. It is typically
generated by the server on successful creation of a resource and is
not allowed to change on PUT operations. Populated by the system.
Read-only.
type: str
users:
description:
- Users is the list of users in this group.
type: list
contains: str
kind:
description:
- Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to. Cannot
be updated. In CamelCase.
type: str
metadata:
description:
- Standard object's metadata.
type: complex
contains:
resource_version:
description:
- String that identifies the server's internal version of this object that
can be used by clients to determine when objects have changed. Value must
be treated as opaque by clients and passed unmodified back to the server.
Populated by the system. Read-only.
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated by the system. Read-only.
type: str
'''
def main():
try:
module = OpenShiftAnsibleModule('group_list', 'v1')
except OpenShiftAnsibleException as exc:
# The helper failed to init, so there is no module object. All we can do is raise the error.
raise Exception(exc.message)
try:
module.execute_module()
except OpenShiftAnsibleException as exc:
module.fail_json(msg="Module failed!", error=str(exc))
if __name__ == '__main__':
main()
| 47.247423 | 100 | 0.560201 |
from ansible.module_utils.openshift_common import OpenShiftAnsibleModule, OpenShiftAnsibleException
DOCUMENTATION = '''
module: openshift_v1_group_list
short_description: OpenShift GroupList
description:
- Retrieve a list of groups. List operations provide a snapshot read of the underlying
objects, returning a resource_version representing a consistent version of the listed
objects.
version_added: 2.3.0
author: OpenShift (@openshift)
options:
api_key:
description:
- Token used to connect to the API.
cert_file:
description:
- Path to a certificate used to authenticate with the API.
type: path
context:
description:
- The name of a context found in the Kubernetes config file.
debug:
description:
- Enable debug output from the OpenShift helper. Logging info is written to KubeObjHelper.log
default: false
type: bool
force:
description:
- If set to C(True), and I(state) is C(present), an existing object will updated,
and lists will be replaced, rather than merged.
default: false
type: bool
host:
description:
- Provide a URL for acessing the Kubernetes API.
key_file:
description:
- Path to a key file used to authenticate with the API.
type: path
kubeconfig:
description:
- Path to an existing Kubernetes config file. If not provided, and no other connection
options are provided, the openshift client will attempt to load the default
configuration file from I(~/.kube/config.json).
type: path
password:
description:
- Provide a password for connecting to the API. Use in conjunction with I(username).
resource_definition:
description:
- Provide the YAML definition for the object, bypassing any modules parameters
intended to define object attributes.
type: dict
src:
description:
- Provide a path to a file containing the YAML definition of the object. Mutually
exclusive with I(resource_definition).
type: path
ssl_ca_cert:
description:
- Path to a CA certificate used to authenticate with the API.
type: path
state:
description:
- Determines if an object should be created, patched, or deleted. When set to
C(present), the object will be created, if it does not exist, or patched, if
parameter values differ from the existing object's attributes, and deleted,
if set to C(absent). A patch operation results in merging lists and updating
dictionaries, with lists being merged into a unique set of values. If a list
contains a dictionary with a I(name) or I(type) attribute, a strategic merge
is performed, where individual elements with a matching I(name_) or I(type)
are merged. To force the replacement of lists, set the I(force) option to C(True).
default: present
choices:
- present
- absent
username:
description:
- Provide a username for connecting to the API.
verify_ssl:
description:
- Whether or not to verify the API server's SSL certificates.
type: bool
requirements:
- openshift == 0.3.3
'''
EXAMPLES = '''
'''
RETURN = '''
api_version:
type: string
description: Requested API version
group_list:
type: complex
returned: when I(state) = C(present)
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values.
type: str
items:
description:
- Items is the list of groups
type: list
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value,
and may reject unrecognized values.
type: str
kind:
description:
- Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to.
Cannot be updated. In CamelCase.
type: str
metadata:
description:
- Standard object's metadata.
type: complex
contains:
annotations:
description:
- Annotations is an unstructured key value map stored with a resource
that may be set by external tools to store and retrieve arbitrary
metadata. They are not queryable and should be preserved when modifying
objects.
type: complex
contains: str, str
cluster_name:
description:
- The name of the cluster which the object belongs to. This is used
to distinguish resources with same name and namespace in different
clusters. This field is not set anywhere right now and apiserver is
going to ignore it if set in create or update request.
type: str
creation_timestamp:
description:
- CreationTimestamp is a timestamp representing the server time when
this object was created. It is not guaranteed to be set in happens-before
order across separate operations. Clients may not set this value.
It is represented in RFC3339 form and is in UTC. Populated by the
system. Read-only. Null for lists.
type: complex
contains: {}
deletion_grace_period_seconds:
description:
- Number of seconds allowed for this object to gracefully terminate
before it will be removed from the system. Only set when deletionTimestamp
is also set. May only be shortened. Read-only.
type: int
deletion_timestamp:
description:
- DeletionTimestamp is RFC 3339 date and time at which this resource
will be deleted. This field is set by the server when a graceful deletion
is requested by the user, and is not directly settable by a client.
The resource is expected to be deleted (no longer visible from resource
lists, and not reachable by name) after the time in this field. Once
set, this value may not be unset or be set further into the future,
although it may be shortened or the resource may be deleted prior
to this time. For example, a user may request that a pod is deleted
in 30 seconds. The Kubelet will react by sending a graceful termination
signal to the containers in the pod. After that 30 seconds, the Kubelet
will send a hard termination signal (SIGKILL) to the container and
after cleanup, remove the pod from the API. In the presence of network
partitions, this object may still exist after this timestamp, until
an administrator or automated process can determine the resource is
fully terminated. If not set, graceful deletion of the object has
not been requested. Populated by the system when a graceful deletion
is requested. Read-only.
type: complex
contains: {}
finalizers:
description:
- Must be empty before the object is deleted from the registry. Each
entry is an identifier for the responsible component that will remove
the entry from the list. If the deletionTimestamp of the object is
non-nil, entries in this list can only be removed.
type: list
contains: str
generate_name:
description:
- GenerateName is an optional prefix, used by the server, to generate
a unique name ONLY IF the Name field has not been provided. If this
field is used, the name returned to the client will be different than
the name passed. This value will also be combined with a unique suffix.
The provided value has the same validation rules as the Name field,
and may be truncated by the length of the suffix required to make
the value unique on the server. If this field is specified and the
generated name exists, the server will NOT return a 409 - instead,
it will either return 201 Created or 500 with Reason ServerTimeout
indicating a unique name could not be found in the time allotted,
and the client should retry (optionally after the time indicated in
the Retry-After header). Applied only if Name is not specified.
type: str
generation:
description:
- A sequence number representing a specific generation of the desired
state. Populated by the system. Read-only.
type: int
initializers:
description:
- An initializer is a controller which enforces some system invariant
at object creation time. This field is a list of initializers that
have not yet acted on this object. If nil or empty, this object has
been completely initialized. Otherwise, the object is considered uninitialized
and is hidden (in list/watch and get calls) from clients that haven't
explicitly asked to observe uninitialized objects. When an object
is created, the system will populate this list with the current set
of initializers. Only privileged users may set or modify this list.
Once it is empty, it may not be modified further by any user.
type: complex
contains:
pending:
description:
- Pending is a list of initializers that must execute in order before
this object is visible. When the last pending initializer is removed,
and no failing result is set, the initializers struct will be
set to nil and the object is considered as initialized and visible
to all clients.
type: list
contains:
name:
description:
- name of the process that is responsible for initializing this
object.
type: str
result:
description:
- If result is set with the Failure field, the object will be persisted
to storage and then deleted, ensuring that other clients can observe
the deletion.
type: complex
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation
of an object. Servers should convert recognized schemas to
the latest internal value, and may reject unrecognized values.
type: str
code:
description:
- Suggested HTTP return code for this status, 0 if not set.
type: int
details:
description:
- Extended data associated with the reason. Each reason may
define its own extended details. This field is optional and
the data returned is not guaranteed to conform to any schema
except that defined by the reason type.
type: complex
contains:
causes:
description:
- The Causes array includes more details associated with
the StatusReason failure. Not all StatusReasons may provide
detailed causes.
type: list
contains:
field:
description:
- 'The field of the resource that has caused this error,
as named by its JSON serialization. May include dot
and postfix notation for nested attributes. Arrays
are zero-indexed. Fields may appear more than once
in an array of causes due to fields having multiple
errors. Optional. Examples: "name" - the field "name"
on the current resource "items[0].name" - the field
"name" on the first array entry in "items"'
type: str
message:
description:
- A human-readable description of the cause of the error.
This field may be presented as-is to a reader.
type: str
reason:
description:
- A machine-readable description of the cause of the
error. If this value is empty there is no information
available.
type: str
group:
description:
- The group attribute of the resource associated with the
status StatusReason.
type: str
kind:
description:
- The kind attribute of the resource associated with the
status StatusReason. On some operations may differ from
the requested resource Kind.
type: str
name:
description:
- The name attribute of the resource associated with the
status StatusReason (when there is a single name which
can be described).
type: str
retry_after_seconds:
description:
- If specified, the time in seconds before the operation
should be retried.
type: int
uid:
description:
- UID of the resource. (when there is a single resource
which can be described).
type: str
kind:
description:
- Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint
the client submits requests to. Cannot be updated. In CamelCase.
type: str
message:
description:
- A human-readable description of the status of this operation.
type: str
metadata:
description:
- Standard list metadata.
type: complex
contains:
resource_version:
description:
- String that identifies the server's internal version of
this object that can be used by clients to determine when
objects have changed. Value must be treated as opaque
by clients and passed unmodified back to the server. Populated
by the system. Read-only.
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated
by the system. Read-only.
type: str
reason:
description:
- A machine-readable description of why this operation is in
the "Failure" status. If this value is empty there is no information
available. A Reason clarifies an HTTP status code but does
not override it.
type: str
status:
description:
- 'Status of the operation. One of: "Success" or "Failure".'
type: str
labels:
description:
- Map of string keys and values that can be used to organize and categorize
(scope and select) objects. May match selectors of replication controllers
and services.
type: complex
contains: str, str
name:
description:
- Name must be unique within a namespace. Is required when creating
resources, although some resources may allow a client to request the
generation of an appropriate name automatically. Name is primarily
intended for creation idempotence and configuration definition. Cannot
be updated.
type: str
namespace:
description:
- Namespace defines the space within each name must be unique. An empty
namespace is equivalent to the "default" namespace, but "default"
is the canonical representation. Not all objects are required to be
scoped to a namespace - the value of this field for those objects
will be empty. Must be a DNS_LABEL. Cannot be updated.
type: str
owner_references:
description:
- List of objects depended by this object. If ALL objects in the list
have been deleted, this object will be garbage collected. If this
object is managed by a controller, then an entry in this list will
point to this controller, with the controller field set to true. There
cannot be more than one managing controller.
type: list
contains:
api_version:
description:
- API version of the referent.
type: str
block_owner_deletion:
description:
- If true, AND if the owner has the "foregroundDeletion" finalizer,
then the owner cannot be deleted from the key-value store until
this reference is removed. Defaults to false. To set this field,
a user needs "delete" permission of the owner, otherwise 422 (Unprocessable
Entity) will be returned.
type: bool
controller:
description:
- If true, this reference points to the managing controller.
type: bool
kind:
description:
- Kind of the referent.
type: str
name:
description:
- Name of the referent.
type: str
uid:
description:
- UID of the referent.
type: str
resource_version:
description:
- An opaque value that represents the internal version of this object
that can be used by clients to determine when objects have changed.
May be used for optimistic concurrency, change detection, and the
watch operation on a resource or set of resources. Clients must treat
these values as opaque and passed unmodified back to the server. They
may only be valid for a particular resource or set of resources. Populated
by the system. Read-only. Value must be treated as opaque by clients
and .
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated by the system.
Read-only.
type: str
uid:
description:
- UID is the unique in time and space value for this object. It is typically
generated by the server on successful creation of a resource and is
not allowed to change on PUT operations. Populated by the system.
Read-only.
type: str
users:
description:
- Users is the list of users in this group.
type: list
contains: str
kind:
description:
- Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to. Cannot
be updated. In CamelCase.
type: str
metadata:
description:
- Standard object's metadata.
type: complex
contains:
resource_version:
description:
- String that identifies the server's internal version of this object that
can be used by clients to determine when objects have changed. Value must
be treated as opaque by clients and passed unmodified back to the server.
Populated by the system. Read-only.
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated by the system. Read-only.
type: str
'''
def main():
try:
module = OpenShiftAnsibleModule('group_list', 'v1')
except OpenShiftAnsibleException as exc:
# The helper failed to init, so there is no module object. All we can do is raise the error.
raise Exception(exc.message)
try:
module.execute_module()
except OpenShiftAnsibleException as exc:
module.fail_json(msg="Module failed!", error=str(exc))
if __name__ == '__main__':
main()
| true | true |
f72c1d801a02316cde52c7ee09431a992b7ae36e | 2,353 | py | Python | research/delf/delf/python/examples/detector.py | 873040/Abhishek | 2ddd716e66bc5cc6e6f0787508dd07da0e02e75a | [
"Apache-2.0"
] | 6 | 2020-01-15T09:55:24.000Z | 2021-04-22T09:03:46.000Z | research/delf/delf/python/examples/detector.py | 873040/Abhishek | 2ddd716e66bc5cc6e6f0787508dd07da0e02e75a | [
"Apache-2.0"
] | 10 | 2019-12-28T21:31:19.000Z | 2020-04-12T20:01:58.000Z | research/delf/delf/python/examples/detector.py | 873040/Abhishek | 2ddd716e66bc5cc6e6f0787508dd07da0e02e75a | [
"Apache-2.0"
] | 8 | 2020-04-12T04:30:33.000Z | 2021-09-17T20:54:44.000Z | # Copyright 2019 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.
# ==============================================================================
"""Module to construct object detector function."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def MakeDetector(sess, model_dir, import_scope=None):
"""Creates a function to detect objects in an image.
Args:
sess: TensorFlow session to use.
model_dir: Directory where SavedModel is located.
import_scope: Optional scope to use for model.
Returns:
Function that receives an image and returns detection results.
"""
tf.saved_model.loader.load(
sess, [tf.saved_model.tag_constants.SERVING],
model_dir,
import_scope=import_scope)
import_scope_prefix = import_scope + '/' if import_scope is not None else ''
input_images = sess.graph.get_tensor_by_name('%sinput_images:0' %
import_scope_prefix)
boxes = sess.graph.get_tensor_by_name('%sdetection_boxes:0' %
import_scope_prefix)
scores = sess.graph.get_tensor_by_name('%sdetection_scores:0' %
import_scope_prefix)
class_indices = sess.graph.get_tensor_by_name('%sdetection_classes:0' %
import_scope_prefix)
def DetectorFn(images):
"""Receives an image and returns detected boxes.
Args:
images: Uint8 array with shape (batch, height, width 3) containing a batch
of RGB images.
Returns:
Tuple (boxes, scores, class_indices).
"""
return sess.run([boxes, scores, class_indices],
feed_dict={input_images: images})
return DetectorFn
| 37.349206 | 80 | 0.663408 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def MakeDetector(sess, model_dir, import_scope=None):
tf.saved_model.loader.load(
sess, [tf.saved_model.tag_constants.SERVING],
model_dir,
import_scope=import_scope)
import_scope_prefix = import_scope + '/' if import_scope is not None else ''
input_images = sess.graph.get_tensor_by_name('%sinput_images:0' %
import_scope_prefix)
boxes = sess.graph.get_tensor_by_name('%sdetection_boxes:0' %
import_scope_prefix)
scores = sess.graph.get_tensor_by_name('%sdetection_scores:0' %
import_scope_prefix)
class_indices = sess.graph.get_tensor_by_name('%sdetection_classes:0' %
import_scope_prefix)
def DetectorFn(images):
return sess.run([boxes, scores, class_indices],
feed_dict={input_images: images})
return DetectorFn
| true | true |
f72c1ec91f3364c0ca6dca97ad1176f0456b92a7 | 5,633 | py | Python | ceph_install/rhel/u130/src/prereq/MonPrereq.py | rpratap-bot/ceph-qe-scripts | 8a7090d6707a8e7b927eabfc9c9212f343a35bc4 | [
"MIT"
] | null | null | null | ceph_install/rhel/u130/src/prereq/MonPrereq.py | rpratap-bot/ceph-qe-scripts | 8a7090d6707a8e7b927eabfc9c9212f343a35bc4 | [
"MIT"
] | null | null | null | ceph_install/rhel/u130/src/prereq/MonPrereq.py | rpratap-bot/ceph-qe-scripts | 8a7090d6707a8e7b927eabfc9c9212f343a35bc4 | [
"MIT"
] | null | null | null | import os
import utils.log as log
import time
class EnableRepos(object):
def __init__(self,host, qa_username, qa_password, pool_id):
self.username = qa_username
self.password = qa_password
self.poolid = pool_id
self.host = host
self.ssh = 'ssh %s ' %host.hostname # do not forget add space after the format specifier
def enable_rhel_repo(self):
print "Subscribing to RHEL rpms"
self.unregister = " 'sudo subscription-manager unregister' "
self.register_node = " 'sudo subscription-manager register --username %s --password %s' " % (self.username, self.password)
self.refresh_node = " 'sudo subscription-manager refresh' "
self.attach_poolid = " 'sudo subscription-manager attach --pool=%s' " % (self.poolid)
self.enable_repo = " 'sudo subscription-manager repos --enable=rhel-7-server-rpms' "
self.yum_update = " 'sudo yum update -y' "
return self.unregister, self.register_node, self.refresh_node, self.attach_poolid, self.enable_repo, self.yum_update,
def execute(self):
print "Enabling the repos"
commands = self.enable_rhel_repo()
for command in commands:
command = self.ssh + command
log.info("Enabling RHEL repos in Mon Node")
log.debug(command)
os.system(command)
class MonFireWallSettings(object):
def __init__(self,host):
self.host = host
self.ssh = 'ssh %s ' %host.hostname # do not forget add space after the format specifier
def firewall_settings_commands(self):
print 'in Mon firewall' # format to specifiy the command: " '<command>' "
self.start_firewalld = " ' sudo systemctl start firewalld' "
self.enable_firewalld = " ' sudo systemctl enable firewalld' "
self.verify_firewalld = "' sudo systemctl status firewalld.service' "
self.open_6789 = " 'sudo firewall-cmd --zone=public --add-port=6789/tcp --permanent' "
self.saveiptables = " 'sudo firewall-cmd --reload' "
return self.start_firewalld, self.enable_firewalld, self.verify_firewalld, self.open_6789, self.saveiptables,
def execute(self):
print 'in admin execute'
commands = self.firewall_settings_commands()
for command in commands:
command = self.ssh + command
log.info('execting firewall settings in Mon node with command')
log.debug(command)
os.system(command)
class InstallNTP(object):
def __init__(self,host):
self.host = host
self.ssh = 'ssh %s ' %host.hostname # do not forget add space after the format specifier
def install_ntp_commands(self):
print 'Installing NTP'
self.install_ntp = " 'sudo yum install ntp -y' "
self.enable_ntp = " 'sudo systemctl enable ntpd.service' "
self.start_ntp = " 'sudo systemctl start ntpd' "
self.verify_ntp = " 'sudo systemctl status ntpd' "
self.ntp_sync = " 'sudo ntpq -p' "
return self.install_ntp, self. enable_ntp, self.start_ntp, self.verify_ntp, self.ntp_sync,
def execute(self):
print 'Installing NTP on Mon Node'
commands = self.install_ntp_commands()
for command in commands:
command = self.ssh + command
log.info('Installing NTP in Mon Node ')
log.debug(command)
os.system(command)
class DisableSelinux(object):
def __init__(self,host):
self.host = host
self.ssh = 'ssh %s ' %host.hostname
def disable_selinux_commands(self):
print "Disable Selinux"
self.disable_cli = " 'sudo setenforce 0'"
self.disable_config = " 'sudo sed -i s/SELINUX=enforcing/SELINUX=permissive/ /etc/selinux/config' "
return self.disable_cli, self.disable_config,
def execute(self):
print 'Disabling Selinux'
commands = self.disable_selinux_commands()
for command in commands:
command = self.ssh + command
log.info('Disabling Selinux ')
log.debug(command)
os.system(command)
class Adjustpid(object):
def __init__(self,host):
self.host = host
self.ssh = 'ssh %s ' %host.hostname
def adjust_pid_command(self):
print "adjust pid"
self.modify = " 'echo 4194303 | sudo tee /proc/sys/kernel/pid_max' "
self.save_changes = " 'sudo sysctl -p' "
return self.modify, self.save_changes,
def execute(self):
print 'adjust pid'
commands = self.adjust_pid_command()
for command in commands:
command = self.ssh + command
log.info('adjust pid')
log.debug(command)
os.system(command)
class DoMonSettings(object):
def __init__(self, mons, creds):
self.mons = mons
self.qa_username = creds['qa_username']
self.qa_password = creds['qa_password']
self.pool_id = creds['pool_id']
def do_settings(self):
log.info('in mon pre settings')
for each_mon in self.mons:
time.sleep(5)
add_repos = EnableRepos(each_mon, self.qa_username, self.qa_password, self.pool_id)
add_repos.execute()
firewall_setting = MonFireWallSettings(each_mon)
firewall_setting.execute()
install_ntp = InstallNTP(each_mon)
install_ntp.execute()
disable_selinux = DisableSelinux(each_mon)
disable_selinux.execute()
adjust_pid = Adjustpid(each_mon)
adjust_pid.execute()
| 33.135294 | 130 | 0.628972 | import os
import utils.log as log
import time
class EnableRepos(object):
def __init__(self,host, qa_username, qa_password, pool_id):
self.username = qa_username
self.password = qa_password
self.poolid = pool_id
self.host = host
self.ssh = 'ssh %s ' %host.hostname
def enable_rhel_repo(self):
print "Subscribing to RHEL rpms"
self.unregister = " 'sudo subscription-manager unregister' "
self.register_node = " 'sudo subscription-manager register --username %s --password %s' " % (self.username, self.password)
self.refresh_node = " 'sudo subscription-manager refresh' "
self.attach_poolid = " 'sudo subscription-manager attach --pool=%s' " % (self.poolid)
self.enable_repo = " 'sudo subscription-manager repos --enable=rhel-7-server-rpms' "
self.yum_update = " 'sudo yum update -y' "
return self.unregister, self.register_node, self.refresh_node, self.attach_poolid, self.enable_repo, self.yum_update,
def execute(self):
print "Enabling the repos"
commands = self.enable_rhel_repo()
for command in commands:
command = self.ssh + command
log.info("Enabling RHEL repos in Mon Node")
log.debug(command)
os.system(command)
class MonFireWallSettings(object):
def __init__(self,host):
self.host = host
self.ssh = 'ssh %s ' %host.hostname
def firewall_settings_commands(self):
print 'in Mon firewall'
self.start_firewalld = " ' sudo systemctl start firewalld' "
self.enable_firewalld = " ' sudo systemctl enable firewalld' "
self.verify_firewalld = "' sudo systemctl status firewalld.service' "
self.open_6789 = " 'sudo firewall-cmd --zone=public --add-port=6789/tcp --permanent' "
self.saveiptables = " 'sudo firewall-cmd --reload' "
return self.start_firewalld, self.enable_firewalld, self.verify_firewalld, self.open_6789, self.saveiptables,
def execute(self):
print 'in admin execute'
commands = self.firewall_settings_commands()
for command in commands:
command = self.ssh + command
log.info('execting firewall settings in Mon node with command')
log.debug(command)
os.system(command)
class InstallNTP(object):
def __init__(self,host):
self.host = host
self.ssh = 'ssh %s ' %host.hostname
def install_ntp_commands(self):
print 'Installing NTP'
self.install_ntp = " 'sudo yum install ntp -y' "
self.enable_ntp = " 'sudo systemctl enable ntpd.service' "
self.start_ntp = " 'sudo systemctl start ntpd' "
self.verify_ntp = " 'sudo systemctl status ntpd' "
self.ntp_sync = " 'sudo ntpq -p' "
return self.install_ntp, self. enable_ntp, self.start_ntp, self.verify_ntp, self.ntp_sync,
def execute(self):
print 'Installing NTP on Mon Node'
commands = self.install_ntp_commands()
for command in commands:
command = self.ssh + command
log.info('Installing NTP in Mon Node ')
log.debug(command)
os.system(command)
class DisableSelinux(object):
def __init__(self,host):
self.host = host
self.ssh = 'ssh %s ' %host.hostname
def disable_selinux_commands(self):
print "Disable Selinux"
self.disable_cli = " 'sudo setenforce 0'"
self.disable_config = " 'sudo sed -i s/SELINUX=enforcing/SELINUX=permissive/ /etc/selinux/config' "
return self.disable_cli, self.disable_config,
def execute(self):
print 'Disabling Selinux'
commands = self.disable_selinux_commands()
for command in commands:
command = self.ssh + command
log.info('Disabling Selinux ')
log.debug(command)
os.system(command)
class Adjustpid(object):
def __init__(self,host):
self.host = host
self.ssh = 'ssh %s ' %host.hostname
def adjust_pid_command(self):
print "adjust pid"
self.modify = " 'echo 4194303 | sudo tee /proc/sys/kernel/pid_max' "
self.save_changes = " 'sudo sysctl -p' "
return self.modify, self.save_changes,
def execute(self):
print 'adjust pid'
commands = self.adjust_pid_command()
for command in commands:
command = self.ssh + command
log.info('adjust pid')
log.debug(command)
os.system(command)
class DoMonSettings(object):
def __init__(self, mons, creds):
self.mons = mons
self.qa_username = creds['qa_username']
self.qa_password = creds['qa_password']
self.pool_id = creds['pool_id']
def do_settings(self):
log.info('in mon pre settings')
for each_mon in self.mons:
time.sleep(5)
add_repos = EnableRepos(each_mon, self.qa_username, self.qa_password, self.pool_id)
add_repos.execute()
firewall_setting = MonFireWallSettings(each_mon)
firewall_setting.execute()
install_ntp = InstallNTP(each_mon)
install_ntp.execute()
disable_selinux = DisableSelinux(each_mon)
disable_selinux.execute()
adjust_pid = Adjustpid(each_mon)
adjust_pid.execute()
| false | true |
f72c1f06d6b7f222137806f0a368da2e76782f5f | 1,411 | py | Python | project-EE/run_cleaning.py | Mariagca/EscapeEarth | 5c57ff9dc1a1aed8a3d74d664287f54746c85dff | [
"MIT"
] | 2 | 2020-10-08T20:47:36.000Z | 2020-12-12T22:20:41.000Z | project-EE/run_cleaning.py | Mariagca/EscapeEarth | 5c57ff9dc1a1aed8a3d74d664287f54746c85dff | [
"MIT"
] | null | null | null | project-EE/run_cleaning.py | Mariagca/EscapeEarth | 5c57ff9dc1a1aed8a3d74d664287f54746c85dff | [
"MIT"
] | 6 | 2020-10-08T21:18:23.000Z | 2020-10-08T21:34:35.000Z | #imports
import cleaning_modules as cm
import os
#BE SURE TO CHOOSE OR AMEND THE 'rawdatapath' & 'filename_danielle' paths for your computer!!
# our inputs
tic_list = [7582594, 7582633, 7620704, 7618785, 7584049]
sectornumber = 14
rawdatapath = '/Users/helenfellow/Desktop/sec14_rawdata_subsample/'
rawdatapath_danielle = '/Users/helenfellow/Desktop/sec14_rawdata_subsample/'
cleandata, cleanticids = cm.Dataclean(tic_list,sectornumber,rawdatapath)
#data = cleaned data as a lightkurve class object
for count, i in enumerate(cleanticids):
tic = i
data = cleandata[count]
filename_danielle = '/Users/helenfellow/Desktop/Internship/{}/lc.fits'.format(tic)
filename_maria= '/Users/helenfellow/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_elise = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_olivia = '~/Desktop/Brown Scholars/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_sarah = '~/Desktop/AMNH/BridgeUp Internship/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_anna_claire = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_eliza = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
#commentout
os.makedirs(os.path.dirname(filename_danielle), exist_ok=True) #verify/make folder with tic_id as the name
data.to_fits(filename_danielle,flux_column_name = 'flux',overwrite=True);
| 45.516129 | 110 | 0.764706 |
import cleaning_modules as cm
import os
tic_list = [7582594, 7582633, 7620704, 7618785, 7584049]
sectornumber = 14
rawdatapath = '/Users/helenfellow/Desktop/sec14_rawdata_subsample/'
rawdatapath_danielle = '/Users/helenfellow/Desktop/sec14_rawdata_subsample/'
cleandata, cleanticids = cm.Dataclean(tic_list,sectornumber,rawdatapath)
for count, i in enumerate(cleanticids):
tic = i
data = cleandata[count]
filename_danielle = '/Users/helenfellow/Desktop/Internship/{}/lc.fits'.format(tic)
filename_maria= '/Users/helenfellow/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_elise = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_olivia = '~/Desktop/Brown Scholars/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_sarah = '~/Desktop/AMNH/BridgeUp Internship/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_anna_claire = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_eliza = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
os.makedirs(os.path.dirname(filename_danielle), exist_ok=True)
data.to_fits(filename_danielle,flux_column_name = 'flux',overwrite=True);
| true | true |
f72c1f9c72b57af7309945959a0c4b2f24dee261 | 631 | py | Python | elk_project/manage.py | joyliao07/elk | c697d6847c57c0e7f3b4dc71a373c5fe0407e237 | [
"MIT"
] | null | null | null | elk_project/manage.py | joyliao07/elk | c697d6847c57c0e7f3b4dc71a373c5fe0407e237 | [
"MIT"
] | 7 | 2019-12-04T23:17:25.000Z | 2021-06-09T17:54:51.000Z | elk_project/manage.py | joyliao07/elk | c697d6847c57c0e7f3b4dc71a373c5fe0407e237 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'elk_project.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)
if __name__ == '__main__':
main()
| 28.681818 | 75 | 0.684628 |
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'elk_project.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)
if __name__ == '__main__':
main()
| true | true |
f72c1fde1011d3abd20dca04a582e9d40af5f026 | 911 | py | Python | heap sort.py | angelopassaro/Hacktoberfest-1 | 21f90f5d49efba9b1a27f4d9b923f5017ab43f0e | [
"Apache-2.0"
] | 1 | 2020-10-06T01:20:07.000Z | 2020-10-06T01:20:07.000Z | heap sort.py | angelopassaro/Hacktoberfest-1 | 21f90f5d49efba9b1a27f4d9b923f5017ab43f0e | [
"Apache-2.0"
] | null | null | null | heap sort.py | angelopassaro/Hacktoberfest-1 | 21f90f5d49efba9b1a27f4d9b923f5017ab43f0e | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# coding: utf-8
# In[4]:
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def heapSort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
# Driver code to test above
arr = [ 12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print ("%d" %arr[i]),
# This code is contributed by Mohit Kumra
# In[ ]:
| 17.862745 | 51 | 0.556531 |
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
arr = [ 12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print ("%d" %arr[i]),
| true | true |
f72c206e11dd63945aef32da40727635e29f68fe | 3,204 | py | Python | tests/sources/test_url.py | mikewcasale/climetlab | 924aa602dcd638ff1a49a9d8b4b6f7bd29361d1e | [
"Apache-2.0"
] | null | null | null | tests/sources/test_url.py | mikewcasale/climetlab | 924aa602dcd638ff1a49a9d8b4b6f7bd29361d1e | [
"Apache-2.0"
] | null | null | null | tests/sources/test_url.py | mikewcasale/climetlab | 924aa602dcd638ff1a49a9d8b4b6f7bd29361d1e | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
# (C) Copyright 2020 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
#
import datetime
import mimetypes
import os
import sys
import pytest
from climetlab import load_source
from climetlab.sources.url import canonical_extension
from climetlab.testing import climetlab_file
@pytest.mark.skipif( # TODO: fix
sys.platform == "win32",
reason="file:// not working on Windows yet",
)
def test_url_file_source():
filename = os.path.abspath(climetlab_file("docs/examples/test.nc"))
s = load_source("url", f"file://{filename}")
assert len(s) == 2
def test_url_ftp_source_anonymous():
date = datetime.datetime.now() - datetime.timedelta(days=1)
load_source(
"url-pattern",
(
"ftp://ftp.ncep.noaa.gov/pub/data/nccf/com/gfs/prod/"
"gfs.{date:date(%Y%m%d)}/00/atmos/wafsgfs_P_t00z_intdsk84.grib2"
),
{"date": date},
)
def test_url_ftp_source_with_user_pass():
import ftplib
date = datetime.datetime.now() - datetime.timedelta(days=1)
try:
load_source(
"url-pattern",
(
"ftp://wmo:essential@dissemination.ecmwf.int/{date:date(%Y%m%d)}000000/"
"A_HPXA89ECMF{date:date(%d)}0000_C_ECMF_{date:date(%Y%m%d)}"
"000000_an_msl_global_0p5deg_grib2.bin"
),
{"date": date},
)
except ftplib.error_temp:
# Sometimes this site returns:
# ftplib.error_temp: 421 Maximum number of connections exceeded (500)
pass
def test_url_source_1():
load_source(
"url",
"http://download.ecmwf.int/test-data/metview/gallery/temp.bufr",
)
def test_url_source_2():
load_source(
"url",
"https://github.com/ecmwf/climetlab/raw/master/docs/examples/test.grib",
)
def test_url_source_3():
load_source(
"url",
"https://github.com/ecmwf/climetlab/raw/master/docs/examples/test.nc",
)
def test_mimetypes():
assert mimetypes.guess_type("x.grib") == ("application/x-grib", None)
assert canonical_extension("x.grib") == ".grib"
assert canonical_extension("x.grib1") == ".grib"
assert canonical_extension("x.grib2") == ".grib"
assert mimetypes.guess_type("x.nc") == ("application/x-netcdf", None)
assert canonical_extension("x.nc") == ".nc"
assert canonical_extension("x.nc4") == ".nc"
assert canonical_extension("x.cdf") == ".nc"
assert canonical_extension("x.netcdf") == ".nc"
def test_canonical_extension():
assert canonical_extension("x.tar") == ".tar"
assert canonical_extension("x.tgz") == ".tar.gz"
assert canonical_extension("x.foo") == ".foo"
assert canonical_extension("x.csv") == ".csv"
assert canonical_extension("x.csv.gz") == ".csv.gz"
if __name__ == "__main__":
from climetlab.testing import main
main(globals())
| 28.607143 | 88 | 0.652934 |
import datetime
import mimetypes
import os
import sys
import pytest
from climetlab import load_source
from climetlab.sources.url import canonical_extension
from climetlab.testing import climetlab_file
@pytest.mark.skipif(
sys.platform == "win32",
reason="file:// not working on Windows yet",
)
def test_url_file_source():
filename = os.path.abspath(climetlab_file("docs/examples/test.nc"))
s = load_source("url", f"file://{filename}")
assert len(s) == 2
def test_url_ftp_source_anonymous():
date = datetime.datetime.now() - datetime.timedelta(days=1)
load_source(
"url-pattern",
(
"ftp://ftp.ncep.noaa.gov/pub/data/nccf/com/gfs/prod/"
"gfs.{date:date(%Y%m%d)}/00/atmos/wafsgfs_P_t00z_intdsk84.grib2"
),
{"date": date},
)
def test_url_ftp_source_with_user_pass():
import ftplib
date = datetime.datetime.now() - datetime.timedelta(days=1)
try:
load_source(
"url-pattern",
(
"ftp://wmo:essential@dissemination.ecmwf.int/{date:date(%Y%m%d)}000000/"
"A_HPXA89ECMF{date:date(%d)}0000_C_ECMF_{date:date(%Y%m%d)}"
"000000_an_msl_global_0p5deg_grib2.bin"
),
{"date": date},
)
except ftplib.error_temp:
pass
def test_url_source_1():
load_source(
"url",
"http://download.ecmwf.int/test-data/metview/gallery/temp.bufr",
)
def test_url_source_2():
load_source(
"url",
"https://github.com/ecmwf/climetlab/raw/master/docs/examples/test.grib",
)
def test_url_source_3():
load_source(
"url",
"https://github.com/ecmwf/climetlab/raw/master/docs/examples/test.nc",
)
def test_mimetypes():
assert mimetypes.guess_type("x.grib") == ("application/x-grib", None)
assert canonical_extension("x.grib") == ".grib"
assert canonical_extension("x.grib1") == ".grib"
assert canonical_extension("x.grib2") == ".grib"
assert mimetypes.guess_type("x.nc") == ("application/x-netcdf", None)
assert canonical_extension("x.nc") == ".nc"
assert canonical_extension("x.nc4") == ".nc"
assert canonical_extension("x.cdf") == ".nc"
assert canonical_extension("x.netcdf") == ".nc"
def test_canonical_extension():
assert canonical_extension("x.tar") == ".tar"
assert canonical_extension("x.tgz") == ".tar.gz"
assert canonical_extension("x.foo") == ".foo"
assert canonical_extension("x.csv") == ".csv"
assert canonical_extension("x.csv.gz") == ".csv.gz"
if __name__ == "__main__":
from climetlab.testing import main
main(globals())
| true | true |
f72c2077893d50552e9dcf77f984503151020b67 | 2,825 | py | Python | Testing/Alignment.py | freder/PageBotExamples | eb4ced53a673b9376e8357afa9ea0795b022b13c | [
"Ruby",
"MIT"
] | 5 | 2020-06-20T22:01:23.000Z | 2021-08-06T04:39:50.000Z | Testing/Alignment.py | freder/PageBotExamples | eb4ced53a673b9376e8357afa9ea0795b022b13c | [
"Ruby",
"MIT"
] | 5 | 2020-05-17T09:32:27.000Z | 2021-03-15T19:45:52.000Z | Testing/Alignment.py | freder/PageBotExamples | eb4ced53a673b9376e8357afa9ea0795b022b13c | [
"Ruby",
"MIT"
] | 2 | 2021-02-25T19:07:45.000Z | 2022-01-09T21:14:06.000Z | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T E X A M P L E S
#
# Copyright (c) 2017 Thom Janssen <https://github.com/thomgb>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyxyz.org/flat
# -----------------------------------------------------------------------------
#
# TODO: Floating on second line does not seem to work currently
from pagebot.toolbox.color import color
from pagebot import getContext
EXPORT_PATH = '_export/Start'
# Export in _export folder that does not commit in Git.
# Force to export to a few file formats:
EXPORT_PATH_PDF = EXPORT_PATH + '.pdf'
EXPORT_PATH_JPG = EXPORT_PATH + '.jpg'
EXPORT_PATH_PNG = EXPORT_PATH + '.png'
EXPORT_PATH_SVG = EXPORT_PATH + '.svg'
# Document is the main instance holding all information about the document
# together (pages, styles, etc.)
from pagebot.document import Document
from pagebot.elements import *
from pagebot.conditions import *
from pagebot.toolbox.color import Color
W, H = 500, 400
def makeDocument(context):
# Creates the publication/document that holds the pages.
doc = Document(w=W, h=H, context=context)
print(doc.view)
print(doc.pages)
doc.view.padding = 0 # Don't show cropmarks in this example.
#doc.margin =
doc.view.showPadding = True
c1 = [Right2Right(), Float2Top(), Float2Left()]
c2 = [Right2Right(), Float2Top()]
c3 = [Left2Left()]
c4 = [Left2Left(), Float2TopLeft()]
c5 = [Right2Right(), Float2TopLeft()]
c6 = [Left2Left(), Float2TopRight()]
conditions = [c1]#, c2]#, c3, c4, c5, c6]
page = doc[1]
for c in conditions:
makePage(doc, page, c)
#page = page.next
testCoordinates(context)
rectSets = []
def makePage(doc, page, conditions):
# Gets page by pageNumber, first in row (at this point there is only one in
# this row).
page.padding = 1
page.showPadding = True
numberOfSquares = 8
ratio = 1 / numberOfSquares
rects = []
for n in range(numberOfSquares):
r = newRect(w=40, h=42, mr=4, mt=4, parent=page,
fill=color(1 - n*ratio, 0, 0.5),
conditions=conditions, margin=0)
rects.append(r)
rectSets.append(rects)
score = doc.solve()
doc.build()
def testCoordinates(context):
context.fill((0, 1, 0))
context.stroke(None)
for rects in rectSets:
i = 0
for r in rects:
i +=1
x = r.getFloatSideLeft()
y = r.getFloatSideTop()
#print('%d %d' % (x, y))
context.circle(x, y, 2)
context.text('%d' % i, (x + 5, y - 5))
context = getContext()
makeDocument(context)
| 27.163462 | 79 | 0.593982 |
from pagebot.toolbox.color import color
from pagebot import getContext
EXPORT_PATH = '_export/Start'
EXPORT_PATH_PDF = EXPORT_PATH + '.pdf'
EXPORT_PATH_JPG = EXPORT_PATH + '.jpg'
EXPORT_PATH_PNG = EXPORT_PATH + '.png'
EXPORT_PATH_SVG = EXPORT_PATH + '.svg'
from pagebot.document import Document
from pagebot.elements import *
from pagebot.conditions import *
from pagebot.toolbox.color import Color
W, H = 500, 400
def makeDocument(context):
doc = Document(w=W, h=H, context=context)
print(doc.view)
print(doc.pages)
doc.view.padding = 0
#doc.margin =
doc.view.showPadding = True
c1 = [Right2Right(), Float2Top(), Float2Left()]
c2 = [Right2Right(), Float2Top()]
c3 = [Left2Left()]
c4 = [Left2Left(), Float2TopLeft()]
c5 = [Right2Right(), Float2TopLeft()]
c6 = [Left2Left(), Float2TopRight()]
conditions = [c1]#, c2]#, c3, c4, c5, c6]
page = doc[1]
for c in conditions:
makePage(doc, page, c)
#page = page.next
testCoordinates(context)
rectSets = []
def makePage(doc, page, conditions):
# Gets page by pageNumber, first in row (at this point there is only one in
# this row).
page.padding = 1
page.showPadding = True
numberOfSquares = 8
ratio = 1 / numberOfSquares
rects = []
for n in range(numberOfSquares):
r = newRect(w=40, h=42, mr=4, mt=4, parent=page,
fill=color(1 - n*ratio, 0, 0.5),
conditions=conditions, margin=0)
rects.append(r)
rectSets.append(rects)
score = doc.solve()
doc.build()
def testCoordinates(context):
context.fill((0, 1, 0))
context.stroke(None)
for rects in rectSets:
i = 0
for r in rects:
i +=1
x = r.getFloatSideLeft()
y = r.getFloatSideTop()
#print('%d %d' % (x, y))
context.circle(x, y, 2)
context.text('%d' % i, (x + 5, y - 5))
context = getContext()
makeDocument(context)
| true | true |
f72c210c8aaaf5a73cd82343cc65417943d52979 | 13,090 | py | Python | geofabric/model/catchment.py | CSIRO-enviro-informatics/geofabric-dataset | fbca2c79a8e7532f751fb51bebd3433c42d9f422 | [
"Apache-2.0"
] | 3 | 2019-07-16T14:07:54.000Z | 2020-07-04T17:55:24.000Z | geofabric/model/catchment.py | CSIRO-enviro-informatics/geofabric-dataset | fbca2c79a8e7532f751fb51bebd3433c42d9f422 | [
"Apache-2.0"
] | 24 | 2018-09-20T05:17:32.000Z | 2021-12-13T19:49:50.000Z | geofabric/model/catchment.py | CSIRO-enviro-informatics/geofabric-dataset | fbca2c79a8e7532f751fb51bebd3433c42d9f422 | [
"Apache-2.0"
] | 3 | 2018-10-23T05:58:22.000Z | 2019-11-03T23:04:35.000Z | # -*- coding: utf-8 -*-
#
import rdflib
from urllib.request import Request, urlopen
from flask import render_template, url_for
from lxml.etree import ParseError
from rdflib import URIRef, Literal, BNode
from lxml import etree
from geofabric import _config as config
from geofabric.helpers import gml_extract_geom_to_geojson, \
wfs_extract_features_as_geojson, \
wfs_extract_features_as_profile, gml_extract_geom_to_geosparql, \
GEO_hasGeometry, GEO_hasDefaultGeometry, RDF_a, \
HYF_HY_CatchmentRealization, HYF_realizedCatchment, HYF_lowerCatchment, \
HYF_catchmentRealization, HYF_HY_Catchment, HYF_HY_HydroFeature, \
calculate_bbox, NotFoundError
from geofabric.model import GFModel
from functools import lru_cache
from datetime import datetime
# TODO: look into using cachetools.LFUCache or TTLCache
@lru_cache(maxsize=128)
def retrieve_catchment(identifier):
assert isinstance(identifier, int)
catchment_wfs_uri = config.GF_OWS_ENDPOINT + \
'?request=GetFeature' \
'&service=WFS' \
'&version=2.0.0' \
'&typeName=ahgf_shcatch:AHGFCatchment' \
'&Filter=<Filter><PropertyIsEqualTo>' \
'<PropertyName>ahgf_shcatch:hydroid</PropertyName>' \
'<Literal>{:d}</Literal>' \
'</PropertyIsEqualTo></Filter>'.format(identifier)
try:
r = Request(catchment_wfs_uri, method="GET")
with urlopen(r) as response: # type: http.client.HTTPResponse
if not (299 >= response.status >= 200):
raise RuntimeError(
"Cannot get Catchment from WFS backend.")
try:
tree = etree.parse(response)
except ParseError as e:
print(e)
print(response.read())
return []
except Exception as e:
raise e
return tree
ns = {
'x': 'http://linked.data.gov.au/dataset/geof/v2/ahgf_shcatch',
'wfs': 'http://www.opengis.net/wfs/2.0',
'gml': "http://www.opengis.net/gml/3.2"
}
catchment_tag_map = {
"{{{}}}hydroid".format(ns['x']): 'hydroid',
"{{{}}}wkb_geometry".format(ns['x']): 'wkb_geometry',
"{{{}}}ahgfftype".format(ns['x']): 'ahgfftype',
"{{{}}}netnodeid".format(ns['x']): 'netnodeid',
"{{{}}}ncb_id".format(ns['x']): 'ncb_id',
"{{{}}}segmentno".format(ns['x']): 'segmentno',
"{{{}}}streamname".format(ns['x']): 'streamname',
"{{{}}}hassegment".format(ns['x']): 'hassegment',
"{{{}}}extrnlbasn".format(ns['x']): 'extrnlbasn',
"{{{}}}nextdownid".format(ns['x']): 'nextdownid',
"{{{}}}srcfcname".format(ns['x']): 'srcfcname',
"{{{}}}srcfctype".format(ns['x']): 'srcfctype',
"{{{}}}sourceid".format(ns['x']): 'sourceid',
"{{{}}}featrel".format(ns['x']): 'featrel',
"{{{}}}fsource".format(ns['x']): 'fsource',
"{{{}}}attrrel".format(ns['x']): 'attrrel',
"{{{}}}attrsource".format(ns['x']): 'attrsource',
"{{{}}}planacc".format(ns['x']): 'planacc',
"{{{}}}albersarea".format(ns['x']): 'albersarea',
"{{{}}}shape_length".format(ns['x']): 'shape_length',
"{{{}}}shape_area".format(ns['x']): 'shape_area',
"{{{}}}shape".format(ns['x']): 'shape',
}
def catchment_hyfeatures_converter(wfs_features):
if len(wfs_features) < 1:
return None
to_converter = {
'wkb_geometry': gml_extract_geom_to_geosparql,
'shape': gml_extract_geom_to_geosparql,
'nextdownid': lambda x: (set(), URIRef("".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE, x.text]))),
}
to_float = ('shape_length', 'shape_area', 'albersarea')
to_int = ('hydroid', 'ahgfftype', 'netnodeid', 'ncb_id', 'segmentno', 'sourceid')
to_datetime = ('attrrel', 'featrel')
is_geom = ('wkb_geometry', 'shape')
predicate_map = {
'nextdownid': HYF_lowerCatchment
}
features_list = []
if isinstance(wfs_features, (dict,)):
features_source = wfs_features.items()
elif isinstance(wfs_features, (list, set)):
features_source = iter(wfs_features)
else:
features_source = [wfs_features]
triples = set()
feature_nodes = []
for hydroid, catchment_element in features_source: # type: int, etree._Element
feature_uri = rdflib.URIRef(
"".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE,
str(hydroid)]))
triples.add((feature_uri, RDF_a, HYF_HY_HydroFeature))
triples.add((feature_uri, RDF_a, HYF_HY_Catchment))
for c in catchment_element.iterchildren(): # type: etree._Element
try:
var = catchment_tag_map[c.tag]
except KeyError:
continue
try:
conv_func = to_converter[var]
_triples, val = conv_func(c)
for (s, p, o) in iter(_triples):
triples.add((s, p, o))
except KeyError:
val = c.text
if var in to_datetime:
if val.endswith('Z'):
val = val[:-1]
try:
val = datetime.strptime(val, "%Y-%m-%dT%H:%M:%S")
val = Literal(val)
except ValueError:
val = "Invalid time format"
elif var in to_float:
val = Literal(float(val))
elif var in to_int:
val = Literal(int(val))
else:
if not isinstance(val, (URIRef, Literal, BNode)):
val = Literal(str(val))
if var in is_geom:
realization = BNode()
triples.add((realization, RDF_a, HYF_HY_CatchmentRealization))
triples.add((realization, GEO_hasGeometry, val))
triples.add((realization, HYF_realizedCatchment, feature_uri))
triples.add((feature_uri, HYF_catchmentRealization, realization))
#triples.add((feature_uri, GEO_hasDefaultGeometry, var))
elif var in predicate_map.keys():
predicate = predicate_map[var]
triples.add((feature_uri, predicate, val))
else:
dummy_prop = URIRef("{}/{}".format(ns['x'], var))
triples.add((feature_uri, dummy_prop, val))
features_list.append(feature_uri)
return triples, feature_nodes
def catchment_features_geojson_converter(wfs_features):
if len(wfs_features) < 1:
return None
to_converter = {
'wkb_geometry': gml_extract_geom_to_geojson,
'shape': gml_extract_geom_to_geojson,
}
to_float = ('shape_length', 'shape_area', 'albersarea')
to_int = ('hydroid', 'ahgfftype', 'netnodeid', 'ncb_id', 'segmentno', 'nextdownid', 'sourceid')
# to_datetime = ('attrrel', 'featrel')
to_datetime = []
is_geom = ('wkb_geometry', 'shape')
features_list = []
if isinstance(wfs_features, (dict,)):
features_source = wfs_features.items()
elif isinstance(wfs_features, (list, set)):
features_source = iter(wfs_features)
else:
features_source = [wfs_features]
for hydroid, catchment_element in features_source: # type: int, etree._Element
catchment_dict = {"type": "Feature", "id": hydroid, "geometry": {}, "properties": {}}
for c in catchment_element.iterchildren(): # type: etree._Element
try:
var = catchment_tag_map[c.tag]
except KeyError:
continue
try:
conv_func = to_converter[var]
val = conv_func(c)
except KeyError:
val = c.text
if var in to_datetime:
if val.endswith('Z'):
val = val[:-1]
try:
val = datetime.strptime(val, "%Y-%m-%dT%H:%M:%S")
except ValueError:
val = "Invalid time format"
elif var in to_float:
val = float(val)
elif var in to_int:
val = int(val)
if var in is_geom:
catchment_dict['geometry'] = val
else:
catchment_dict['properties'][var] = val
features_list.append(catchment_dict)
return features_list
def extract_catchments_as_geojson(tree):
geojson_features = wfs_extract_features_as_geojson(tree, ns['x'], "AHGFCatchment", catchment_features_geojson_converter)
return geojson_features
def extract_catchments_as_hyfeatures(tree, model=None):
g = rdflib.Graph()
triples, features = wfs_extract_features_as_profile(tree, ns['x'], "AHGFCatchment", catchment_hyfeatures_converter, model)
for (s, p, o) in iter(triples):
g.add((s, p, o))
return g
class Catchment(GFModel):
@classmethod
def make_instance_label(cls, instance_id):
return "Catchment ID: {}".format(str(instance_id))
@classmethod
def make_canonical_uri(cls, instance_id):
return "".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE, instance_id])
@classmethod
def make_local_url(cls, instance_id):
return url_for('classes.catchment', contractedcatchment_id=instance_id)
@classmethod
def get_index(cls, page, per_page):
per_page = max(int(per_page), 1)
offset = (max(int(page), 1)-1)*per_page
catchments_wfs_uri = config.GF_OWS_ENDPOINT + \
'?service=wfs' \
'&version=2.0.0' \
'&request=GetFeature' \
'&typeName=ahgf_shcatch:AHGFCatchment' \
'&propertyName=hydroid' \
'&sortBy=hydroid' \
'&count={}&startIndex={}'.format(per_page, offset)
try:
r = Request(catchments_wfs_uri, method="GET")
with urlopen(r) as response: # type: http.client.HTTPResponse
if not (299 >= response.status >= 200):
raise RuntimeError("Cannot get Contracted Catchments index from WFS backend.")
try:
tree = etree.parse(response)
except ParseError as e:
print(e)
print(response.read())
return []
except Exception as e:
raise e
items = tree.xpath('//x:hydroid/text()', namespaces={
'x': 'http://linked.data.gov.au/dataset/geof/v2/ahgf_shcatch'})
return items
def __init__(self, identifier):
super(Catchment, self).__init__()
identifier = int(identifier)
catchment_xml_tree = retrieve_catchment(identifier)
self.xml_tree = catchment_xml_tree
catchments = extract_catchments_as_geojson(catchment_xml_tree)
if catchments['features'] is None or len(catchments['features']) < 1:
raise NotFoundError()
catchment = catchments['features'][0]
self.geometry = catchment['geometry']
for k, v in catchment['properties'].items():
setattr(self, k, v)
def get_bbox(self, pad=0):
coords = self.geometry['coordinates']
json_bbox = calculate_bbox(coords, pad=pad)
(n, s, e, w) = json_bbox
return (w,s,e,n) # (minx, miny, maxx, maxy)
def to_hyfeatures_graph(self):
g = extract_catchments_as_hyfeatures(self.xml_tree)
return g
def export_html(self, view='geofabric'):
bbox_string = ",".join(str(i) for i in self.get_bbox(pad=12))
hydroid = self.hydroid
wms_url = config.GF_OWS_ENDPOINT +\
"?service=wms&version=2.0.0&request=GetMap" \
"&width=800&height=600" \
"&format=text/html;+subtype=openlayers" \
"&CRS=EPSG:4326" \
"&layers=osm_au,ahgf_shcatch:AHGFCatchment" \
"&style=ahgfcatchment" \
"&bbox=" + bbox_string +\
"&CQL_FILTER=INCLUDE;hydroid="+str(hydroid)
nextdownid = getattr(self, 'nextdownid', None)
if view == 'geofabric':
view_html = render_template(
'class_catchment_geof.html',
wms_url=wms_url,
hydroid=hydroid,
nextdownid=nextdownid,
shape_length=self.shape_length,
shape_area=self.shape_area,
albers_area=self.albersarea,
)
elif view == "hyfeatures":
view_html = render_template(
'class_catchment_hyf.html',
wms_url=wms_url,
hydroid=hydroid,
nextdownid=nextdownid,
shape_length=self.shape_length,
shape_area=self.shape_area,
albers_area=self.albersarea,
)
else:
return NotImplementedError("HTML representation of View '{}' is not implemented.".format(view))
return view_html
| 40.526316 | 126 | 0.572193 |
import rdflib
from urllib.request import Request, urlopen
from flask import render_template, url_for
from lxml.etree import ParseError
from rdflib import URIRef, Literal, BNode
from lxml import etree
from geofabric import _config as config
from geofabric.helpers import gml_extract_geom_to_geojson, \
wfs_extract_features_as_geojson, \
wfs_extract_features_as_profile, gml_extract_geom_to_geosparql, \
GEO_hasGeometry, GEO_hasDefaultGeometry, RDF_a, \
HYF_HY_CatchmentRealization, HYF_realizedCatchment, HYF_lowerCatchment, \
HYF_catchmentRealization, HYF_HY_Catchment, HYF_HY_HydroFeature, \
calculate_bbox, NotFoundError
from geofabric.model import GFModel
from functools import lru_cache
from datetime import datetime
@lru_cache(maxsize=128)
def retrieve_catchment(identifier):
assert isinstance(identifier, int)
catchment_wfs_uri = config.GF_OWS_ENDPOINT + \
'?request=GetFeature' \
'&service=WFS' \
'&version=2.0.0' \
'&typeName=ahgf_shcatch:AHGFCatchment' \
'&Filter=<Filter><PropertyIsEqualTo>' \
'<PropertyName>ahgf_shcatch:hydroid</PropertyName>' \
'<Literal>{:d}</Literal>' \
'</PropertyIsEqualTo></Filter>'.format(identifier)
try:
r = Request(catchment_wfs_uri, method="GET")
with urlopen(r) as response:
if not (299 >= response.status >= 200):
raise RuntimeError(
"Cannot get Catchment from WFS backend.")
try:
tree = etree.parse(response)
except ParseError as e:
print(e)
print(response.read())
return []
except Exception as e:
raise e
return tree
ns = {
'x': 'http://linked.data.gov.au/dataset/geof/v2/ahgf_shcatch',
'wfs': 'http://www.opengis.net/wfs/2.0',
'gml': "http://www.opengis.net/gml/3.2"
}
catchment_tag_map = {
"{{{}}}hydroid".format(ns['x']): 'hydroid',
"{{{}}}wkb_geometry".format(ns['x']): 'wkb_geometry',
"{{{}}}ahgfftype".format(ns['x']): 'ahgfftype',
"{{{}}}netnodeid".format(ns['x']): 'netnodeid',
"{{{}}}ncb_id".format(ns['x']): 'ncb_id',
"{{{}}}segmentno".format(ns['x']): 'segmentno',
"{{{}}}streamname".format(ns['x']): 'streamname',
"{{{}}}hassegment".format(ns['x']): 'hassegment',
"{{{}}}extrnlbasn".format(ns['x']): 'extrnlbasn',
"{{{}}}nextdownid".format(ns['x']): 'nextdownid',
"{{{}}}srcfcname".format(ns['x']): 'srcfcname',
"{{{}}}srcfctype".format(ns['x']): 'srcfctype',
"{{{}}}sourceid".format(ns['x']): 'sourceid',
"{{{}}}featrel".format(ns['x']): 'featrel',
"{{{}}}fsource".format(ns['x']): 'fsource',
"{{{}}}attrrel".format(ns['x']): 'attrrel',
"{{{}}}attrsource".format(ns['x']): 'attrsource',
"{{{}}}planacc".format(ns['x']): 'planacc',
"{{{}}}albersarea".format(ns['x']): 'albersarea',
"{{{}}}shape_length".format(ns['x']): 'shape_length',
"{{{}}}shape_area".format(ns['x']): 'shape_area',
"{{{}}}shape".format(ns['x']): 'shape',
}
def catchment_hyfeatures_converter(wfs_features):
if len(wfs_features) < 1:
return None
to_converter = {
'wkb_geometry': gml_extract_geom_to_geosparql,
'shape': gml_extract_geom_to_geosparql,
'nextdownid': lambda x: (set(), URIRef("".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE, x.text]))),
}
to_float = ('shape_length', 'shape_area', 'albersarea')
to_int = ('hydroid', 'ahgfftype', 'netnodeid', 'ncb_id', 'segmentno', 'sourceid')
to_datetime = ('attrrel', 'featrel')
is_geom = ('wkb_geometry', 'shape')
predicate_map = {
'nextdownid': HYF_lowerCatchment
}
features_list = []
if isinstance(wfs_features, (dict,)):
features_source = wfs_features.items()
elif isinstance(wfs_features, (list, set)):
features_source = iter(wfs_features)
else:
features_source = [wfs_features]
triples = set()
feature_nodes = []
for hydroid, catchment_element in features_source:
feature_uri = rdflib.URIRef(
"".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE,
str(hydroid)]))
triples.add((feature_uri, RDF_a, HYF_HY_HydroFeature))
triples.add((feature_uri, RDF_a, HYF_HY_Catchment))
for c in catchment_element.iterchildren():
try:
var = catchment_tag_map[c.tag]
except KeyError:
continue
try:
conv_func = to_converter[var]
_triples, val = conv_func(c)
for (s, p, o) in iter(_triples):
triples.add((s, p, o))
except KeyError:
val = c.text
if var in to_datetime:
if val.endswith('Z'):
val = val[:-1]
try:
val = datetime.strptime(val, "%Y-%m-%dT%H:%M:%S")
val = Literal(val)
except ValueError:
val = "Invalid time format"
elif var in to_float:
val = Literal(float(val))
elif var in to_int:
val = Literal(int(val))
else:
if not isinstance(val, (URIRef, Literal, BNode)):
val = Literal(str(val))
if var in is_geom:
realization = BNode()
triples.add((realization, RDF_a, HYF_HY_CatchmentRealization))
triples.add((realization, GEO_hasGeometry, val))
triples.add((realization, HYF_realizedCatchment, feature_uri))
triples.add((feature_uri, HYF_catchmentRealization, realization))
elif var in predicate_map.keys():
predicate = predicate_map[var]
triples.add((feature_uri, predicate, val))
else:
dummy_prop = URIRef("{}/{}".format(ns['x'], var))
triples.add((feature_uri, dummy_prop, val))
features_list.append(feature_uri)
return triples, feature_nodes
def catchment_features_geojson_converter(wfs_features):
if len(wfs_features) < 1:
return None
to_converter = {
'wkb_geometry': gml_extract_geom_to_geojson,
'shape': gml_extract_geom_to_geojson,
}
to_float = ('shape_length', 'shape_area', 'albersarea')
to_int = ('hydroid', 'ahgfftype', 'netnodeid', 'ncb_id', 'segmentno', 'nextdownid', 'sourceid')
to_datetime = []
is_geom = ('wkb_geometry', 'shape')
features_list = []
if isinstance(wfs_features, (dict,)):
features_source = wfs_features.items()
elif isinstance(wfs_features, (list, set)):
features_source = iter(wfs_features)
else:
features_source = [wfs_features]
for hydroid, catchment_element in features_source:
catchment_dict = {"type": "Feature", "id": hydroid, "geometry": {}, "properties": {}}
for c in catchment_element.iterchildren():
try:
var = catchment_tag_map[c.tag]
except KeyError:
continue
try:
conv_func = to_converter[var]
val = conv_func(c)
except KeyError:
val = c.text
if var in to_datetime:
if val.endswith('Z'):
val = val[:-1]
try:
val = datetime.strptime(val, "%Y-%m-%dT%H:%M:%S")
except ValueError:
val = "Invalid time format"
elif var in to_float:
val = float(val)
elif var in to_int:
val = int(val)
if var in is_geom:
catchment_dict['geometry'] = val
else:
catchment_dict['properties'][var] = val
features_list.append(catchment_dict)
return features_list
def extract_catchments_as_geojson(tree):
geojson_features = wfs_extract_features_as_geojson(tree, ns['x'], "AHGFCatchment", catchment_features_geojson_converter)
return geojson_features
def extract_catchments_as_hyfeatures(tree, model=None):
g = rdflib.Graph()
triples, features = wfs_extract_features_as_profile(tree, ns['x'], "AHGFCatchment", catchment_hyfeatures_converter, model)
for (s, p, o) in iter(triples):
g.add((s, p, o))
return g
class Catchment(GFModel):
@classmethod
def make_instance_label(cls, instance_id):
return "Catchment ID: {}".format(str(instance_id))
@classmethod
def make_canonical_uri(cls, instance_id):
return "".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE, instance_id])
@classmethod
def make_local_url(cls, instance_id):
return url_for('classes.catchment', contractedcatchment_id=instance_id)
@classmethod
def get_index(cls, page, per_page):
per_page = max(int(per_page), 1)
offset = (max(int(page), 1)-1)*per_page
catchments_wfs_uri = config.GF_OWS_ENDPOINT + \
'?service=wfs' \
'&version=2.0.0' \
'&request=GetFeature' \
'&typeName=ahgf_shcatch:AHGFCatchment' \
'&propertyName=hydroid' \
'&sortBy=hydroid' \
'&count={}&startIndex={}'.format(per_page, offset)
try:
r = Request(catchments_wfs_uri, method="GET")
with urlopen(r) as response:
if not (299 >= response.status >= 200):
raise RuntimeError("Cannot get Contracted Catchments index from WFS backend.")
try:
tree = etree.parse(response)
except ParseError as e:
print(e)
print(response.read())
return []
except Exception as e:
raise e
items = tree.xpath('//x:hydroid/text()', namespaces={
'x': 'http://linked.data.gov.au/dataset/geof/v2/ahgf_shcatch'})
return items
def __init__(self, identifier):
super(Catchment, self).__init__()
identifier = int(identifier)
catchment_xml_tree = retrieve_catchment(identifier)
self.xml_tree = catchment_xml_tree
catchments = extract_catchments_as_geojson(catchment_xml_tree)
if catchments['features'] is None or len(catchments['features']) < 1:
raise NotFoundError()
catchment = catchments['features'][0]
self.geometry = catchment['geometry']
for k, v in catchment['properties'].items():
setattr(self, k, v)
def get_bbox(self, pad=0):
coords = self.geometry['coordinates']
json_bbox = calculate_bbox(coords, pad=pad)
(n, s, e, w) = json_bbox
return (w,s,e,n)
def to_hyfeatures_graph(self):
g = extract_catchments_as_hyfeatures(self.xml_tree)
return g
def export_html(self, view='geofabric'):
bbox_string = ",".join(str(i) for i in self.get_bbox(pad=12))
hydroid = self.hydroid
wms_url = config.GF_OWS_ENDPOINT +\
"?service=wms&version=2.0.0&request=GetMap" \
"&width=800&height=600" \
"&format=text/html;+subtype=openlayers" \
"&CRS=EPSG:4326" \
"&layers=osm_au,ahgf_shcatch:AHGFCatchment" \
"&style=ahgfcatchment" \
"&bbox=" + bbox_string +\
"&CQL_FILTER=INCLUDE;hydroid="+str(hydroid)
nextdownid = getattr(self, 'nextdownid', None)
if view == 'geofabric':
view_html = render_template(
'class_catchment_geof.html',
wms_url=wms_url,
hydroid=hydroid,
nextdownid=nextdownid,
shape_length=self.shape_length,
shape_area=self.shape_area,
albers_area=self.albersarea,
)
elif view == "hyfeatures":
view_html = render_template(
'class_catchment_hyf.html',
wms_url=wms_url,
hydroid=hydroid,
nextdownid=nextdownid,
shape_length=self.shape_length,
shape_area=self.shape_area,
albers_area=self.albersarea,
)
else:
return NotImplementedError("HTML representation of View '{}' is not implemented.".format(view))
return view_html
| true | true |
f72c2280bf4ad25e6907abd6b677f870efbe0e50 | 1,135 | py | Python | src/models/ep.py | tonyduan/ge-vae | fe3325cb643900d09536b3e1d964443d25625781 | [
"MIT"
] | 7 | 2019-11-04T09:13:44.000Z | 2021-04-22T01:28:27.000Z | src/models/ep.py | tonyduan/ge-vae | fe3325cb643900d09536b3e1d964443d25625781 | [
"MIT"
] | null | null | null | src/models/ep.py | tonyduan/ge-vae | fe3325cb643900d09536b3e1d964443d25625781 | [
"MIT"
] | 3 | 2019-11-02T10:50:29.000Z | 2020-02-09T02:50:48.000Z | import torch
import torch.nn as nn
from torch.distributions import Bernoulli
from src.modules.attn import MAB, PMA, SAB, ISAB, ISABStack
from src.utils import *
from src.modules.mlp import *
class EdgePredictor(nn.Module):
def __init__(self, embedding_dim, device):
super().__init__()
self.pairwise_query = ISABStack(8, embedding_dim, 256, num_heads = 4,
num_inds = 16, device = device)
self.device = device
self.baseline = nn.Parameter(torch.zeros(1, device = device))
self.scale1 = nn.Parameter(torch.zeros(1, device = device))
def forward(self, E, V):
mask = construct_embedding_mask(V).byte()
Z1 = self.pairwise_query(E, mask)
F = Z1 @ Z1.transpose(1, 2)
return F * torch.exp(self.scale1) + self.baseline #+ \
def log_prob_per_edge(self, E, A, V):
mask = construct_adjacency_mask(V)
counts = V * (V - 1) / 2
loss = Bernoulli(logits = self.forward(E, V)).log_prob(A)
loss = torch.sum(torch.triu(loss, diagonal = 1) * mask, dim = (1, 2))
return loss #/ counts
| 35.46875 | 78 | 0.61674 | import torch
import torch.nn as nn
from torch.distributions import Bernoulli
from src.modules.attn import MAB, PMA, SAB, ISAB, ISABStack
from src.utils import *
from src.modules.mlp import *
class EdgePredictor(nn.Module):
def __init__(self, embedding_dim, device):
super().__init__()
self.pairwise_query = ISABStack(8, embedding_dim, 256, num_heads = 4,
num_inds = 16, device = device)
self.device = device
self.baseline = nn.Parameter(torch.zeros(1, device = device))
self.scale1 = nn.Parameter(torch.zeros(1, device = device))
def forward(self, E, V):
mask = construct_embedding_mask(V).byte()
Z1 = self.pairwise_query(E, mask)
F = Z1 @ Z1.transpose(1, 2)
return F * torch.exp(self.scale1) + self.baseline
def log_prob_per_edge(self, E, A, V):
mask = construct_adjacency_mask(V)
counts = V * (V - 1) / 2
loss = Bernoulli(logits = self.forward(E, V)).log_prob(A)
loss = torch.sum(torch.triu(loss, diagonal = 1) * mask, dim = (1, 2))
return loss
| true | true |
f72c22ad9e0dc3e5f4ab51f0e1e77ab067f3acac | 14,720 | py | Python | CybORG/CybORG/Tests/test_sim/test_Actions/test_BlueActions/test_blue_analyse.py | rafvasq/cage-challenge-1 | 95affdfa38afc1124f1a1a09c92fbc0ed5b96318 | [
"MIT"
] | 18 | 2021-08-20T15:07:55.000Z | 2022-03-11T12:05:15.000Z | CybORG/CybORG/Tests/test_sim/test_Actions/test_BlueActions/test_blue_analyse.py | rafvasq/cage-challenge-1 | 95affdfa38afc1124f1a1a09c92fbc0ed5b96318 | [
"MIT"
] | 7 | 2021-11-09T06:46:58.000Z | 2022-03-31T12:35:06.000Z | CybORG/CybORG/Tests/test_sim/test_Actions/test_BlueActions/test_blue_analyse.py | rafvasq/cage-challenge-1 | 95affdfa38afc1124f1a1a09c92fbc0ed5b96318 | [
"MIT"
] | 13 | 2021-08-17T00:26:31.000Z | 2022-03-29T20:06:45.000Z | # These tests check that the Blue Monitor action is working vs Abstract Red Actions.
# tests need to check that a range of inputs result in the correct changes to the state and return the correct obs
# tests should establish varying environmental states that results in these actions performing differently
import inspect
from CybORG import CybORG
from CybORG.Shared.Actions import DiscoverRemoteSystems, DiscoverNetworkServices, ExploitRemoteService, \
PrivilegeEscalate, Impact, Analyse
from CybORG.Shared.Enums import TrinaryEnum, FileType, Path
from CybORG.Tests.EphemeralPort import Win2008EphemeralPort, LinuxEphemeralPort
from CybORG.Tests.test_sim.test_Acceptance.test_reward_function import security_values, availability_values
import pytest
from CybORG.Agents import B_lineAgent
@pytest.mark.skip()
def test_blue_analyse_on_red_killchain(security_values,availability_values):
# create cyborg environment
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = CybORG(path, 'sim')
# Run blue monitor with no red activity.
blue_session = cyborg.get_observation('Blue')['Defender']['Sessions'][0]['ID']
blue_hosts = cyborg.get_action_space('Blue')['hostname']
def blue_analyse(expected_result, host, reward=0.0):
blue_action = Analyse(session=blue_session, agent='Blue', hostname=host)
results = cyborg.step('Blue', blue_action)
assert not results.done
assert results.reward == round(reward, 1)
assert results.observation == expected_result
windows_reverse_shell = {'Density': 0.9,
'File Name': 'cmd.exe',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': 'C:\\temp\\',
'Signed': False}
linux_reverse_shell = {'Density': 0.9,
'File Name': 'cmd.sh',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': '/tmp/',
'Signed': False}
windows_potato_exploit = {'Density': 0.9,
'File Name': 'escalate.exe',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': 'C:\\temp\\',
'Signed': False}
linux_kernel_exploit = {'Density': 0.9,
'File Name': 'escalate.sh',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': '/tmp/',
'Signed': False}
# test discover remote systems
# act on all subnets in action space
action_space = cyborg.get_action_space('Red')
initial_observation = cyborg.get_observation('Red')
session = list(action_space['session'].keys())[0]
for subnet in action_space["subnet"]:
# ping sweep leaves no artifacts for scenario1b
expected_observation = {'success': TrinaryEnum.TRUE}
action = DiscoverRemoteSystems(subnet=subnet, agent='Red', session=session)
cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
for host in blue_hosts:
blue_analyse(expected_observation, host)
# test discover network services
# act on ip addresses discovered in first subnet
addresses = [i for i in action_space["ip_address"]]
attacker_address = cyborg.environment_controller.hostname_ip_map['User0']
for address in addresses:
expected_observation = {'success': TrinaryEnum.TRUE}
action = DiscoverNetworkServices(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
for host in blue_hosts:
blue_analyse(expected_observation, host)
# test exploit action by acting on all known ip_addresses
# own all hosts on the client subnet
reward = 0
for address in addresses:
action = ExploitRemoteService(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
if not action_space["ip_address"][address]:
expected_observation = {'success': TrinaryEnum.TRUE}
elif address == cyborg.environment_controller.hostname_ip_map['User0'] or address == \
cyborg.environment_controller.hostname_ip_map['User1'] or address == \
cyborg.environment_controller.hostname_ip_map['User2']:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
reward += security_values[hostname][0]
elif address == cyborg.environment_controller.hostname_ip_map['User3'] or address == \
cyborg.environment_controller.hostname_ip_map['User4']:
expected_observation = {hostname: {'Files': [linux_reverse_shell]},
'success': TrinaryEnum.TRUE}
else:
raise NotImplementedError
blue_analyse(expected_observation, hostname, reward)
# priv esc on all hosts in client subnet
action_space = cyborg.get_action_space('Red')
hostnames = action_space['hostname']
count = 2
for hostname in hostnames:
action = PrivilegeEscalate(agent='Red', hostname=hostname, session=session)
cyborg.step(action=action, agent='Red')
if hostnames[hostname]:
last_action = cyborg.get_last_action('Red')
assert last_action == action
# test if output of observation matches expected output
if 'User' in hostname:
if '0' in hostname or '1' in hostname or '2' in hostname:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
else:
expected_observation = {hostname: {'Files': [linux_reverse_shell,
linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += security_values[hostname][1]
else:
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, host=hostname, reward=reward)
# recon hosts in enterprise subnet
action_space = cyborg.get_action_space('Red')
addresses = [i for i in action_space["ip_address"]]
for address in addresses:
if not action_space["ip_address"][address] \
or address == cyborg.environment_controller.hostname_ip_map['User0'] \
or address == cyborg.environment_controller.hostname_ip_map['User1'] \
or address == cyborg.environment_controller.hostname_ip_map['User2'] \
or address == cyborg.environment_controller.hostname_ip_map['User3'] \
or address == cyborg.environment_controller.hostname_ip_map['User4']:
continue
else:
expected_observation = {'success': TrinaryEnum.TRUE}
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
action = DiscoverNetworkServices(agent='Red', ip_address=address, session=session)
result = cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
blue_analyse(expected_observation, hostname, reward)
# exploit hosts in enterprise subnet
action_space = cyborg.get_action_space('Red')
addresses = [i for i in action_space["ip_address"]]
for address in addresses:
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
if not action_space["ip_address"][address] \
or address == cyborg.environment_controller.hostname_ip_map['User0'] \
or address == cyborg.environment_controller.hostname_ip_map['User1'] \
or address == cyborg.environment_controller.hostname_ip_map['User2'] \
or address == cyborg.environment_controller.hostname_ip_map['User3'] \
or address == cyborg.environment_controller.hostname_ip_map['User4']:
continue
elif address == cyborg.environment_controller.hostname_ip_map['Enterprise0']:
expected_observation = {'success': TrinaryEnum.TRUE}
count += 1
elif address == cyborg.environment_controller.hostname_ip_map['Enterprise1']:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
count += 1
else:
raise ValueError
action = ExploitRemoteService(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
blue_analyse(expected_observation, hostname, reward)
# priv esc hosts in enterprise subnet
enterprise_subnet = cyborg.environment_controller.subnet_cidr_map['Enterprise']
action_space = cyborg.get_action_space('Red')
hostnames = action_space['hostname']
count = 6
for hostname in hostnames:
if 'User' in hostname:
continue
action = PrivilegeEscalate(agent='Red', hostname=hostname, session=session)
result = cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
if hostname == 'Enterprise0':
expected_observation = {'Enterprise0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
elif hostname == 'Enterprise1':
expected_observation = {'Enterprise1': {'Files': [windows_reverse_shell,
windows_potato_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
else:
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, hostname, reward)
# scan enterprise subnet
action_space = cyborg.get_action_space('Red')
assert enterprise_subnet in action_space['subnet']
assert action_space['subnet'][enterprise_subnet]
action = DiscoverRemoteSystems(agent='Red', subnet=enterprise_subnet, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
# scan the third enterprise host
enterprise2_ip = cyborg.environment_controller.hostname_ip_map['Enterprise2']
assert enterprise2_ip in action_space['ip_address']
assert action_space['ip_address'][enterprise2_ip]
action = DiscoverNetworkServices(agent='Red', ip_address=enterprise2_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
# exploit the 3rd enterprise host
action = ExploitRemoteService(agent='Red', ip_address=enterprise2_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'Enterprise2': {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
# priv esc on enterprise host
assert 'Enterprise2' in action_space['hostname']
assert action_space['hostname']['Enterprise2']
action = PrivilegeEscalate(agent='Red', hostname='Enterprise2', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Enterprise2': {'Files': [windows_reverse_shell,
windows_potato_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
blue_analyse(expected_observation, 'Enterprise2', reward)
# scan the op server
op_server_ip = cyborg.environment_controller.hostname_ip_map['Op_Server0']
assert op_server_ip in action_space['ip_address']
assert action_space['ip_address'][op_server_ip]
action = DiscoverNetworkServices(agent='Red', ip_address=op_server_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward)
# exploit the op server
count = 9
action = ExploitRemoteService(agent='Red', ip_address=op_server_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward)
# priv esc on op server
action = PrivilegeEscalate(agent='Red', hostname='Op_Server0', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Op_Server0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
blue_analyse(expected_observation, 'Op_Server0', reward)
action = Impact(agent='Red', hostname='Op_Server0', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Op_Server0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward=reward-10.0)
@pytest.fixture()
def cyborg(request,agents = {'Red':B_lineAgent},seed = 1):
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = CybORG(path, 'sim', agents=agents)
cyborg.set_seed(seed)
return cyborg
def test_analyse_bug_aug19(cyborg):
cyborg.reset()
for i in range(10):
action = Analyse(session=0,agent='Blue',hostname='Enterprise0')
results = cyborg.step(action=action,agent='Blue')
obs = results.observation
for hostid, host in obs.items():
if hostid == 'success':
continue
if hostid != 'Enterprise0':
assert 'Processes' in host, f'repeats: {i}'
for process in host['Processes']:
assert 'Connections' in process
| 48.580858 | 114 | 0.640014 |
import inspect
from CybORG import CybORG
from CybORG.Shared.Actions import DiscoverRemoteSystems, DiscoverNetworkServices, ExploitRemoteService, \
PrivilegeEscalate, Impact, Analyse
from CybORG.Shared.Enums import TrinaryEnum, FileType, Path
from CybORG.Tests.EphemeralPort import Win2008EphemeralPort, LinuxEphemeralPort
from CybORG.Tests.test_sim.test_Acceptance.test_reward_function import security_values, availability_values
import pytest
from CybORG.Agents import B_lineAgent
@pytest.mark.skip()
def test_blue_analyse_on_red_killchain(security_values,availability_values):
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = CybORG(path, 'sim')
blue_session = cyborg.get_observation('Blue')['Defender']['Sessions'][0]['ID']
blue_hosts = cyborg.get_action_space('Blue')['hostname']
def blue_analyse(expected_result, host, reward=0.0):
blue_action = Analyse(session=blue_session, agent='Blue', hostname=host)
results = cyborg.step('Blue', blue_action)
assert not results.done
assert results.reward == round(reward, 1)
assert results.observation == expected_result
windows_reverse_shell = {'Density': 0.9,
'File Name': 'cmd.exe',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': 'C:\\temp\\',
'Signed': False}
linux_reverse_shell = {'Density': 0.9,
'File Name': 'cmd.sh',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': '/tmp/',
'Signed': False}
windows_potato_exploit = {'Density': 0.9,
'File Name': 'escalate.exe',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': 'C:\\temp\\',
'Signed': False}
linux_kernel_exploit = {'Density': 0.9,
'File Name': 'escalate.sh',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': '/tmp/',
'Signed': False}
action_space = cyborg.get_action_space('Red')
initial_observation = cyborg.get_observation('Red')
session = list(action_space['session'].keys())[0]
for subnet in action_space["subnet"]:
expected_observation = {'success': TrinaryEnum.TRUE}
action = DiscoverRemoteSystems(subnet=subnet, agent='Red', session=session)
cyborg.step(action=action, agent='Red')
for host in blue_hosts:
blue_analyse(expected_observation, host)
addresses = [i for i in action_space["ip_address"]]
attacker_address = cyborg.environment_controller.hostname_ip_map['User0']
for address in addresses:
expected_observation = {'success': TrinaryEnum.TRUE}
action = DiscoverNetworkServices(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
for host in blue_hosts:
blue_analyse(expected_observation, host)
reward = 0
for address in addresses:
action = ExploitRemoteService(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
if not action_space["ip_address"][address]:
expected_observation = {'success': TrinaryEnum.TRUE}
elif address == cyborg.environment_controller.hostname_ip_map['User0'] or address == \
cyborg.environment_controller.hostname_ip_map['User1'] or address == \
cyborg.environment_controller.hostname_ip_map['User2']:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
reward += security_values[hostname][0]
elif address == cyborg.environment_controller.hostname_ip_map['User3'] or address == \
cyborg.environment_controller.hostname_ip_map['User4']:
expected_observation = {hostname: {'Files': [linux_reverse_shell]},
'success': TrinaryEnum.TRUE}
else:
raise NotImplementedError
blue_analyse(expected_observation, hostname, reward)
action_space = cyborg.get_action_space('Red')
hostnames = action_space['hostname']
count = 2
for hostname in hostnames:
action = PrivilegeEscalate(agent='Red', hostname=hostname, session=session)
cyborg.step(action=action, agent='Red')
if hostnames[hostname]:
last_action = cyborg.get_last_action('Red')
assert last_action == action
if 'User' in hostname:
if '0' in hostname or '1' in hostname or '2' in hostname:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
else:
expected_observation = {hostname: {'Files': [linux_reverse_shell,
linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += security_values[hostname][1]
else:
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, host=hostname, reward=reward)
action_space = cyborg.get_action_space('Red')
addresses = [i for i in action_space["ip_address"]]
for address in addresses:
if not action_space["ip_address"][address] \
or address == cyborg.environment_controller.hostname_ip_map['User0'] \
or address == cyborg.environment_controller.hostname_ip_map['User1'] \
or address == cyborg.environment_controller.hostname_ip_map['User2'] \
or address == cyborg.environment_controller.hostname_ip_map['User3'] \
or address == cyborg.environment_controller.hostname_ip_map['User4']:
continue
else:
expected_observation = {'success': TrinaryEnum.TRUE}
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
action = DiscoverNetworkServices(agent='Red', ip_address=address, session=session)
result = cyborg.step(action=action, agent='Red')
blue_analyse(expected_observation, hostname, reward)
action_space = cyborg.get_action_space('Red')
addresses = [i for i in action_space["ip_address"]]
for address in addresses:
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
if not action_space["ip_address"][address] \
or address == cyborg.environment_controller.hostname_ip_map['User0'] \
or address == cyborg.environment_controller.hostname_ip_map['User1'] \
or address == cyborg.environment_controller.hostname_ip_map['User2'] \
or address == cyborg.environment_controller.hostname_ip_map['User3'] \
or address == cyborg.environment_controller.hostname_ip_map['User4']:
continue
elif address == cyborg.environment_controller.hostname_ip_map['Enterprise0']:
expected_observation = {'success': TrinaryEnum.TRUE}
count += 1
elif address == cyborg.environment_controller.hostname_ip_map['Enterprise1']:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
count += 1
else:
raise ValueError
action = ExploitRemoteService(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
blue_analyse(expected_observation, hostname, reward)
enterprise_subnet = cyborg.environment_controller.subnet_cidr_map['Enterprise']
action_space = cyborg.get_action_space('Red')
hostnames = action_space['hostname']
count = 6
for hostname in hostnames:
if 'User' in hostname:
continue
action = PrivilegeEscalate(agent='Red', hostname=hostname, session=session)
result = cyborg.step(action=action, agent='Red')
if hostname == 'Enterprise0':
expected_observation = {'Enterprise0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
elif hostname == 'Enterprise1':
expected_observation = {'Enterprise1': {'Files': [windows_reverse_shell,
windows_potato_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
else:
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, hostname, reward)
action_space = cyborg.get_action_space('Red')
assert enterprise_subnet in action_space['subnet']
assert action_space['subnet'][enterprise_subnet]
action = DiscoverRemoteSystems(agent='Red', subnet=enterprise_subnet, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
enterprise2_ip = cyborg.environment_controller.hostname_ip_map['Enterprise2']
assert enterprise2_ip in action_space['ip_address']
assert action_space['ip_address'][enterprise2_ip]
action = DiscoverNetworkServices(agent='Red', ip_address=enterprise2_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
action = ExploitRemoteService(agent='Red', ip_address=enterprise2_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'Enterprise2': {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
assert 'Enterprise2' in action_space['hostname']
assert action_space['hostname']['Enterprise2']
action = PrivilegeEscalate(agent='Red', hostname='Enterprise2', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Enterprise2': {'Files': [windows_reverse_shell,
windows_potato_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
blue_analyse(expected_observation, 'Enterprise2', reward)
op_server_ip = cyborg.environment_controller.hostname_ip_map['Op_Server0']
assert op_server_ip in action_space['ip_address']
assert action_space['ip_address'][op_server_ip]
action = DiscoverNetworkServices(agent='Red', ip_address=op_server_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward)
count = 9
action = ExploitRemoteService(agent='Red', ip_address=op_server_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward)
action = PrivilegeEscalate(agent='Red', hostname='Op_Server0', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Op_Server0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
blue_analyse(expected_observation, 'Op_Server0', reward)
action = Impact(agent='Red', hostname='Op_Server0', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Op_Server0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward=reward-10.0)
@pytest.fixture()
def cyborg(request,agents = {'Red':B_lineAgent},seed = 1):
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = CybORG(path, 'sim', agents=agents)
cyborg.set_seed(seed)
return cyborg
def test_analyse_bug_aug19(cyborg):
cyborg.reset()
for i in range(10):
action = Analyse(session=0,agent='Blue',hostname='Enterprise0')
results = cyborg.step(action=action,agent='Blue')
obs = results.observation
for hostid, host in obs.items():
if hostid == 'success':
continue
if hostid != 'Enterprise0':
assert 'Processes' in host, f'repeats: {i}'
for process in host['Processes']:
assert 'Connections' in process
| true | true |
f72c237205ee71fae08437e7206ee77f08a6cd89 | 802 | py | Python | mfgp/task2/init_train_idxs.py | kunalghosh/Multi_Fidelity_Prediction_GP | c858554f5c1f0c4aafa12cf7c441bd2d56b115f5 | [
"BSD-3-Clause"
] | null | null | null | mfgp/task2/init_train_idxs.py | kunalghosh/Multi_Fidelity_Prediction_GP | c858554f5c1f0c4aafa12cf7c441bd2d56b115f5 | [
"BSD-3-Clause"
] | 3 | 2021-08-31T08:53:49.000Z | 2021-10-05T15:10:42.000Z | mfgp/task2/init_train_idxs.py | kunalghosh/Multi_Fidelity_Prediction_GP | c858554f5c1f0c4aafa12cf7c441bd2d56b115f5 | [
"BSD-3-Clause"
] | null | null | null | # Run `init_train_idxs.py <int: dataset size> <int: initial training set size>`:
# Creates a `train_idxs.npz` file with the initial set of training indices.
# e.g `python init_train_idxs.py 64000 1000`
import sys
import numpy as np
from sklearn.model_selection import train_test_split
dataset_size = int(sys.argv[1])
init_trainset_size = int(sys.argv[2])
validation_set_size = 500 # usually training set is much larger so 500 is reasonable
np.random.seed(1)
train_idxs, remaining_idxs = train_test_split(range(dataset_size), train_size = init_trainset_size, random_state=0)
valid_idxs, test_idxs = train_test_split(remaining_idxs, train_size = 500, random_state=0)
# save the values in train_idxs.npy
np.savez("train_idxs.npz", train_idxs=train_idxs, valid_idxs=valid_idxs, test_idxs=test_idxs)
| 40.1 | 115 | 0.794264 |
import sys
import numpy as np
from sklearn.model_selection import train_test_split
dataset_size = int(sys.argv[1])
init_trainset_size = int(sys.argv[2])
validation_set_size = 500
np.random.seed(1)
train_idxs, remaining_idxs = train_test_split(range(dataset_size), train_size = init_trainset_size, random_state=0)
valid_idxs, test_idxs = train_test_split(remaining_idxs, train_size = 500, random_state=0)
np.savez("train_idxs.npz", train_idxs=train_idxs, valid_idxs=valid_idxs, test_idxs=test_idxs)
| true | true |
f72c2414f2962eb27d54c0fb810c1358dceaa89f | 3,325 | py | Python | tools/visualize_json_results.py | hhy-ee/PedestrianDetection-NohNMS | 482078a6bd0ff8cf03fbf7f6988e475f75c56e57 | [
"Apache-2.0"
] | null | null | null | tools/visualize_json_results.py | hhy-ee/PedestrianDetection-NohNMS | 482078a6bd0ff8cf03fbf7f6988e475f75c56e57 | [
"Apache-2.0"
] | null | null | null | tools/visualize_json_results.py | hhy-ee/PedestrianDetection-NohNMS | 482078a6bd0ff8cf03fbf7f6988e475f75c56e57 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import json
import numpy as np
import os
from collections import defaultdict
import cv2
import tqdm
from fvcore.common.file_io import PathManager
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.structures import Boxes, BoxMode, Instances
from detectron2.utils.logger import setup_logger
from detectron2.utils.visualizer import Visualizer
def create_instances(predictions, image_size):
ret = Instances(image_size)
score = np.asarray([x["score"] for x in predictions])
chosen = (score > args.conf_threshold).nonzero()[0]
if chosen.shape[0] == 0:
return None
score = score[chosen]
bbox = np.asarray([predictions[i]["bbox"] for i in chosen])
bbox = BoxMode.convert(bbox, BoxMode.XYWH_ABS, BoxMode.XYXY_ABS)
labels = np.asarray([dataset_id_map(predictions[i]["category_id"]) for i in chosen])
ret.scores = score
ret.pred_boxes = Boxes(bbox)
ret.pred_classes = labels
try:
ret.pred_masks = [predictions[i]["segmentation"] for i in chosen]
except KeyError:
pass
return ret
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="A script that visualizes the json predictions from COCO or LVIS dataset."
)
parser.add_argument("--input", required=True, help="JSON file produced by the model")
parser.add_argument("--output", required=True, help="output directory")
parser.add_argument("--dataset", help="name of the dataset", default="coco_2017_val")
parser.add_argument("--conf-threshold", default=0.5, type=float, help="confidence threshold")
args = parser.parse_args()
logger = setup_logger()
with PathManager.open(args.input, "r") as f:
predictions = json.load(f)
pred_by_image = defaultdict(list)
for p in predictions:
pred_by_image[p["image_id"]].append(p)
dicts = list(DatasetCatalog.get(args.dataset))
metadata = MetadataCatalog.get(args.dataset)
if hasattr(metadata, "thing_dataset_id_to_contiguous_id"):
def dataset_id_map(ds_id):
return metadata.thing_dataset_id_to_contiguous_id[ds_id]
elif "lvis" in args.dataset:
# LVIS results are in the same format as COCO results, but have a different
# mapping from dataset category id to contiguous category id in [0, #categories - 1]
def dataset_id_map(ds_id):
return ds_id - 1
else:
raise ValueError("Unsupported dataset: {}".format(args.dataset))
os.makedirs(args.output, exist_ok=True)
for dic in tqdm.tqdm(dicts):
img = cv2.imread(dic["file_name"], cv2.IMREAD_COLOR)[:, :, ::-1]
basename = os.path.basename(dic["file_name"])
predictions = create_instances(pred_by_image[dic["image_id"]], img.shape[:2])
if predictions is not None:
vis = Visualizer(img, metadata)
vis_pred = vis.draw_instance_predictions(predictions).get_image()
else:
vis_pred = img
vis = Visualizer(img, metadata)
vis_gt = vis.draw_dataset_dict(dic).get_image()
concat = np.concatenate((vis_pred, vis_gt), axis=0)
cv2.imwrite(os.path.join(args.output, basename), concat[:, :, ::-1])
| 34.635417 | 97 | 0.687519 |
import argparse
import json
import numpy as np
import os
from collections import defaultdict
import cv2
import tqdm
from fvcore.common.file_io import PathManager
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.structures import Boxes, BoxMode, Instances
from detectron2.utils.logger import setup_logger
from detectron2.utils.visualizer import Visualizer
def create_instances(predictions, image_size):
ret = Instances(image_size)
score = np.asarray([x["score"] for x in predictions])
chosen = (score > args.conf_threshold).nonzero()[0]
if chosen.shape[0] == 0:
return None
score = score[chosen]
bbox = np.asarray([predictions[i]["bbox"] for i in chosen])
bbox = BoxMode.convert(bbox, BoxMode.XYWH_ABS, BoxMode.XYXY_ABS)
labels = np.asarray([dataset_id_map(predictions[i]["category_id"]) for i in chosen])
ret.scores = score
ret.pred_boxes = Boxes(bbox)
ret.pred_classes = labels
try:
ret.pred_masks = [predictions[i]["segmentation"] for i in chosen]
except KeyError:
pass
return ret
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="A script that visualizes the json predictions from COCO or LVIS dataset."
)
parser.add_argument("--input", required=True, help="JSON file produced by the model")
parser.add_argument("--output", required=True, help="output directory")
parser.add_argument("--dataset", help="name of the dataset", default="coco_2017_val")
parser.add_argument("--conf-threshold", default=0.5, type=float, help="confidence threshold")
args = parser.parse_args()
logger = setup_logger()
with PathManager.open(args.input, "r") as f:
predictions = json.load(f)
pred_by_image = defaultdict(list)
for p in predictions:
pred_by_image[p["image_id"]].append(p)
dicts = list(DatasetCatalog.get(args.dataset))
metadata = MetadataCatalog.get(args.dataset)
if hasattr(metadata, "thing_dataset_id_to_contiguous_id"):
def dataset_id_map(ds_id):
return metadata.thing_dataset_id_to_contiguous_id[ds_id]
elif "lvis" in args.dataset:
aset_id_map(ds_id):
return ds_id - 1
else:
raise ValueError("Unsupported dataset: {}".format(args.dataset))
os.makedirs(args.output, exist_ok=True)
for dic in tqdm.tqdm(dicts):
img = cv2.imread(dic["file_name"], cv2.IMREAD_COLOR)[:, :, ::-1]
basename = os.path.basename(dic["file_name"])
predictions = create_instances(pred_by_image[dic["image_id"]], img.shape[:2])
if predictions is not None:
vis = Visualizer(img, metadata)
vis_pred = vis.draw_instance_predictions(predictions).get_image()
else:
vis_pred = img
vis = Visualizer(img, metadata)
vis_gt = vis.draw_dataset_dict(dic).get_image()
concat = np.concatenate((vis_pred, vis_gt), axis=0)
cv2.imwrite(os.path.join(args.output, basename), concat[:, :, ::-1])
| true | true |
f72c262fa25643ba7ad1ef2d7e89c9bd6e9b9e00 | 1,084 | py | Python | redis_cache/compat.py | fu2re/django-redis-cache | 50807ae71bac0714ee625b443205153e9d917e54 | [
"BSD-3-Clause"
] | null | null | null | redis_cache/compat.py | fu2re/django-redis-cache | 50807ae71bac0714ee625b443205153e9d917e54 | [
"BSD-3-Clause"
] | null | null | null | redis_cache/compat.py | fu2re/django-redis-cache | 50807ae71bac0714ee625b443205153e9d917e54 | [
"BSD-3-Clause"
] | 1 | 2020-02-18T13:20:21.000Z | 2020-02-18T13:20:21.000Z | import sys
import django
PY3 = (sys.version_info >= (3,))
try:
# Django 1.5+
from django.utils.encoding import smart_text, smart_bytes
except ImportError:
# older Django, thus definitely Python 2
from django.utils.encoding import smart_unicode, smart_str
smart_text = smart_unicode
smart_bytes = smart_str
if PY3:
bytes_type = bytes
else:
bytes_type = str
if django.VERSION[:2] >= (1, 6):
from django.core.cache.backends.base import DEFAULT_TIMEOUT as DJANGO_DEFAULT_TIMEOUT
DEFAULT_TIMEOUT = DJANGO_DEFAULT_TIMEOUT
else:
DEFAULT_TIMEOUT = None
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
Backported from Django 1.5+.
"""
if not PY3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
| 25.809524 | 89 | 0.714945 | import sys
import django
PY3 = (sys.version_info >= (3,))
try:
from django.utils.encoding import smart_text, smart_bytes
except ImportError:
from django.utils.encoding import smart_unicode, smart_str
smart_text = smart_unicode
smart_bytes = smart_str
if PY3:
bytes_type = bytes
else:
bytes_type = str
if django.VERSION[:2] >= (1, 6):
from django.core.cache.backends.base import DEFAULT_TIMEOUT as DJANGO_DEFAULT_TIMEOUT
DEFAULT_TIMEOUT = DJANGO_DEFAULT_TIMEOUT
else:
DEFAULT_TIMEOUT = None
def python_2_unicode_compatible(klass):
if not PY3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
| true | true |
f72c26bb4fa6463bbf958a86e7df8748e04888fa | 30,608 | py | Python | mwparserfromhell/wikicode.py | TheSandDoctor/mwparserfromhell | de15b8b64497d3386f133400b73dcaf36a131743 | [
"MIT"
] | null | null | null | mwparserfromhell/wikicode.py | TheSandDoctor/mwparserfromhell | de15b8b64497d3386f133400b73dcaf36a131743 | [
"MIT"
] | null | null | null | mwparserfromhell/wikicode.py | TheSandDoctor/mwparserfromhell | de15b8b64497d3386f133400b73dcaf36a131743 | [
"MIT"
] | null | null | null | #
# Copyright (C) 2012-2019 Ben Kurtovic <ben.kurtovic@gmail.com>
#
# 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.
import re
from itertools import chain
from .nodes import (Argument, Comment, ExternalLink, Heading, HTMLEntity,
Node, Tag, Template, Text, Wikilink)
from .smart_list.ListProxy import _ListProxy
from .string_mixin import StringMixIn
from .utils import parse_anything
__all__ = ["Wikicode"]
FLAGS = re.IGNORECASE | re.DOTALL | re.UNICODE
class Wikicode(StringMixIn):
"""A ``Wikicode`` is a container for nodes that operates like a string.
Additionally, it contains methods that can be used to extract data from or
modify the nodes, implemented in an interface similar to a list. For
example, :meth:`index` can get the index of a node in the list, and
:meth:`insert` can add a new node at that index. The :meth:`filter()
<ifilter>` series of functions is very useful for extracting and iterating
over, for example, all of the templates in the object.
"""
RECURSE_OTHERS = 2
def __init__(self, nodes):
super().__init__()
self._nodes = nodes
def __unicode__(self):
return "".join([str(node) for node in self.nodes])
@staticmethod
def _get_children(node, contexts=False, restrict=None, parent=None):
"""Iterate over all child :class:`.Node`\\ s of a given *node*."""
yield (parent, node) if contexts else node
if restrict and isinstance(node, restrict):
return
for code in node.__children__():
for child in code.nodes:
sub = Wikicode._get_children(child, contexts, restrict, code)
yield from sub
@staticmethod
def _slice_replace(code, index, old, new):
"""Replace the string *old* with *new* across *index* in *code*."""
nodes = [str(node) for node in code.get(index)]
substring = "".join(nodes).replace(old, new)
code.nodes[index] = parse_anything(substring).nodes
@staticmethod
def _build_matcher(matches, flags):
"""Helper for :meth:`_indexed_ifilter` and others.
If *matches* is a function, return it. If it's a regex, return a
wrapper around it that can be called with a node to do a search. If
it's ``None``, return a function that always returns ``True``.
"""
if matches:
if callable(matches):
return matches
return lambda obj: re.search(matches, str(obj), flags)
return lambda obj: True
def _indexed_ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
"""Iterate over nodes and their corresponding indices in the node list.
The arguments are interpreted as for :meth:`ifilter`. For each tuple
``(i, node)`` yielded by this method, ``self.index(node) == i``. Note
that if *recursive* is ``True``, ``self.nodes[i]`` might not be the
node itself, but will still contain it.
"""
match = self._build_matcher(matches, flags)
if recursive:
restrict = forcetype if recursive == self.RECURSE_OTHERS else None
def getter(i, node):
for ch in self._get_children(node, restrict=restrict):
yield (i, ch)
inodes = chain(*(getter(i, n) for i, n in enumerate(self.nodes)))
else:
inodes = enumerate(self.nodes)
for i, node in inodes:
if (not forcetype or isinstance(node, forcetype)) and match(node):
yield (i, node)
def _is_child_wikicode(self, obj, recursive=True):
"""Return whether the given :class:`.Wikicode` is a descendant."""
def deref(nodes):
if isinstance(nodes, _ListProxy):
return nodes._parent # pylint: disable=protected-access
return nodes
target = deref(obj.nodes)
if target is deref(self.nodes):
return True
if recursive:
todo = [self]
while todo:
code = todo.pop()
if target is deref(code.nodes):
return True
for node in code.nodes:
todo += list(node.__children__())
return False
def _do_strong_search(self, obj, recursive=True):
"""Search for the specific element *obj* within the node list.
*obj* can be either a :class:`.Node` or a :class:`.Wikicode` object. If
found, we return a tuple (*context*, *index*) where *context* is the
:class:`.Wikicode` that contains *obj* and *index* is its index there,
as a :class:`slice`. Note that if *recursive* is ``False``, *context*
will always be ``self`` (since we only look for *obj* among immediate
descendants), but if *recursive* is ``True``, then it could be any
:class:`.Wikicode` contained by a node within ``self``. If *obj* is not
found, :exc:`ValueError` is raised.
"""
if isinstance(obj, Wikicode):
if not self._is_child_wikicode(obj, recursive):
raise ValueError(obj)
return obj, slice(0, len(obj.nodes))
if isinstance(obj, Node):
mkslice = lambda i: slice(i, i + 1)
if not recursive:
return self, mkslice(self.index(obj))
for node in self.nodes:
for context, child in self._get_children(node, contexts=True):
if obj is child:
if not context:
context = self
return context, mkslice(context.index(child))
raise ValueError(obj)
raise TypeError(obj)
def _do_weak_search(self, obj, recursive):
"""Search for an element that looks like *obj* within the node list.
This follows the same rules as :meth:`_do_strong_search` with some
differences. *obj* is treated as a string that might represent any
:class:`.Node`, :class:`.Wikicode`, or combination of the two present
in the node list. Thus, matching is weak (using string comparisons)
rather than strong (using ``is``). Because multiple nodes can match
*obj*, the result is a list of tuples instead of just one (however,
:exc:`ValueError` is still raised if nothing is found). Individual
matches will never overlap.
The tuples contain a new first element, *exact*, which is ``True`` if
we were able to match *obj* exactly to one or more adjacent nodes, or
``False`` if we found *obj* inside a node or incompletely spanning
multiple nodes.
"""
obj = parse_anything(obj)
if not obj or obj not in self:
raise ValueError(obj)
results = []
contexts = [self]
while contexts:
context = contexts.pop()
i = len(context.nodes) - 1
while i >= 0:
node = context.get(i)
if obj.get(-1) == node:
for j in range(-len(obj.nodes), -1):
if obj.get(j) != context.get(i + j + 1):
break
else:
i -= len(obj.nodes) - 1
index = slice(i, i + len(obj.nodes))
results.append((True, context, index))
elif recursive and obj in node:
contexts.extend(node.__children__())
i -= 1
if not results:
if not recursive:
raise ValueError(obj)
results.append((False, self, slice(0, len(self.nodes))))
return results
def _get_tree(self, code, lines, marker, indent):
"""Build a tree to illustrate the way the Wikicode object was parsed.
The method that builds the actual tree is ``__showtree__`` of ``Node``
objects. *code* is the ``Wikicode`` object to build a tree for. *lines*
is the list to append the tree to, which is returned at the end of the
method. *marker* is some object to be used to indicate that the builder
should continue on from the last line instead of starting a new one; it
should be any object that can be tested for with ``is``. *indent* is
the starting indentation.
"""
def write(*args):
"""Write a new line following the proper indentation rules."""
if lines and lines[-1] is marker: # Continue from the last line
lines.pop() # Remove the marker
last = lines.pop()
lines.append(last + " ".join(args))
else:
lines.append(" " * 6 * indent + " ".join(args))
get = lambda code: self._get_tree(code, lines, marker, indent + 1)
mark = lambda: lines.append(marker)
for node in code.nodes:
node.__showtree__(write, get, mark)
return lines
@classmethod
def _build_filter_methods(cls, **meths):
"""Given Node types, build the corresponding i?filter shortcuts.
The should be given as keys storing the method's base name paired with
values storing the corresponding :class:`.Node` type. For example, the
dict may contain the pair ``("templates", Template)``, which will
produce the methods :meth:`ifilter_templates` and
:meth:`filter_templates`, which are shortcuts for
:meth:`ifilter(forcetype=Template) <ifilter>` and
:meth:`filter(forcetype=Template) <filter>`, respectively. These
shortcuts are added to the class itself, with an appropriate docstring.
"""
doc = """Iterate over {0}.
This is equivalent to :meth:`{1}` with *forcetype* set to
:class:`~{2.__module__}.{2.__name__}`.
"""
make_ifilter = lambda ftype: (lambda self, *a, **kw:
self.ifilter(forcetype=ftype, *a, **kw))
make_filter = lambda ftype: (lambda self, *a, **kw:
self.filter(forcetype=ftype, *a, **kw))
for name, ftype in meths.items():
ifilter = make_ifilter(ftype)
filter = make_filter(ftype)
ifilter.__doc__ = doc.format(name, "ifilter", ftype)
filter.__doc__ = doc.format(name, "filter", ftype)
setattr(cls, "ifilter_" + name, ifilter)
setattr(cls, "filter_" + name, filter)
@property
def nodes(self):
"""A list of :class:`.Node` objects.
This is the internal data actually stored within a :class:`.Wikicode`
object.
"""
return self._nodes
@nodes.setter
def nodes(self, value):
if not isinstance(value, list):
value = parse_anything(value).nodes
self._nodes = value
def get(self, index):
"""Return the *index*\\ th node within the list of nodes."""
return self.nodes[index]
def set(self, index, value):
"""Set the ``Node`` at *index* to *value*.
Raises :exc:`IndexError` if *index* is out of range, or
:exc:`ValueError` if *value* cannot be coerced into one :class:`.Node`.
To insert multiple nodes at an index, use :meth:`get` with either
:meth:`remove` and :meth:`insert` or :meth:`replace`.
"""
nodes = parse_anything(value).nodes
if len(nodes) > 1:
raise ValueError("Cannot coerce multiple nodes into one index")
if index >= len(self.nodes) or -1 * index > len(self.nodes):
raise IndexError("List assignment index out of range")
if nodes:
self.nodes[index] = nodes[0]
else:
self.nodes.pop(index)
def contains(self, obj):
"""Return whether this Wikicode object contains *obj*.
If *obj* is a :class:`.Node` or :class:`.Wikicode` object, then we
search for it exactly among all of our children, recursively.
Otherwise, this method just uses :meth:`.__contains__` on the string.
"""
if not isinstance(obj, (Node, Wikicode)):
return obj in self
try:
self._do_strong_search(obj, recursive=True)
except ValueError:
return False
return True
def index(self, obj, recursive=False):
"""Return the index of *obj* in the list of nodes.
Raises :exc:`ValueError` if *obj* is not found. If *recursive* is
``True``, we will look in all nodes of ours and their descendants, and
return the index of our direct descendant node within *our* list of
nodes. Otherwise, the lookup is done only on direct descendants.
"""
strict = isinstance(obj, Node)
equivalent = (lambda o, n: o is n) if strict else (lambda o, n: o == n)
for i, node in enumerate(self.nodes):
if recursive:
for child in self._get_children(node):
if equivalent(obj, child):
return i
elif equivalent(obj, node):
return i
raise ValueError(obj)
def get_ancestors(self, obj):
"""Return a list of all ancestor nodes of the :class:`.Node` *obj*.
The list is ordered from the most shallow ancestor (greatest great-
grandparent) to the direct parent. The node itself is not included in
the list. For example::
>>> text = "{{a|{{b|{{c|{{d}}}}}}}}"
>>> code = mwparserfromhell.parse(text)
>>> node = code.filter_templates(matches=lambda n: n == "{{d}}")[0]
>>> code.get_ancestors(node)
['{{a|{{b|{{c|{{d}}}}}}}}', '{{b|{{c|{{d}}}}}}', '{{c|{{d}}}}']
Will return an empty list if *obj* is at the top level of this Wikicode
object. Will raise :exc:`ValueError` if it wasn't found.
"""
def _get_ancestors(code, needle):
for node in code.nodes:
if node is needle:
return []
for code in node.__children__():
ancestors = _get_ancestors(code, needle)
if ancestors is not None:
return [node] + ancestors
if isinstance(obj, Wikicode):
obj = obj.get(0)
elif not isinstance(obj, Node):
raise ValueError(obj)
ancestors = _get_ancestors(self, obj)
if ancestors is None:
raise ValueError(obj)
return ancestors
def get_parent(self, obj):
"""Return the direct parent node of the :class:`.Node` *obj*.
This function is equivalent to calling :meth:`.get_ancestors` and
taking the last element of the resulting list. Will return None if
the node exists but does not have a parent; i.e., it is at the top
level of the Wikicode object.
"""
ancestors = self.get_ancestors(obj)
return ancestors[-1] if ancestors else None
def insert(self, index, value):
"""Insert *value* at *index* in the list of nodes.
*value* can be anything parsable by :func:`.parse_anything`, which
includes strings or other :class:`.Wikicode` or :class:`.Node` objects.
"""
nodes = parse_anything(value).nodes
for node in reversed(nodes):
self.nodes.insert(index, node)
def insert_before(self, obj, value, recursive=True):
"""Insert *value* immediately before *obj*.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances of
that string within the code, otherwise only on the specific instance
given. *value* can be anything parsable by :func:`.parse_anything`. If
*recursive* is ``True``, we will try to find *obj* within our child
nodes even if it is not a direct descendant of this :class:`.Wikicode`
object. If *obj* is not found, :exc:`ValueError` is raised.
"""
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
context.insert(index.start, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
context.insert(index.start, value)
else:
obj = str(obj)
self._slice_replace(context, index, obj, str(value) + obj)
def insert_after(self, obj, value, recursive=True):
"""Insert *value* immediately after *obj*.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances of
that string within the code, otherwise only on the specific instance
given. *value* can be anything parsable by :func:`.parse_anything`. If
*recursive* is ``True``, we will try to find *obj* within our child
nodes even if it is not a direct descendant of this :class:`.Wikicode`
object. If *obj* is not found, :exc:`ValueError` is raised.
"""
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
context.insert(index.stop, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
context.insert(index.stop, value)
else:
obj = str(obj)
self._slice_replace(context, index, obj, obj + str(value))
def replace(self, obj, value, recursive=True):
"""Replace *obj* with *value*.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances of
that string within the code, otherwise only on the specific instance
given. *value* can be anything parsable by :func:`.parse_anything`.
If *recursive* is ``True``, we will try to find *obj* within our child
nodes even if it is not a direct descendant of this :class:`.Wikicode`
object. If *obj* is not found, :exc:`ValueError` is raised.
"""
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
context.insert(index.start, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
context.insert(index.start, value)
else:
self._slice_replace(context, index, str(obj), str(value))
def append(self, value):
"""Insert *value* at the end of the list of nodes.
*value* can be anything parsable by :func:`.parse_anything`.
"""
nodes = parse_anything(value).nodes
for node in nodes:
self.nodes.append(node)
def remove(self, obj, recursive=True):
"""Remove *obj* from the list of nodes.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances of
that string within the code, otherwise only on the specific instance
given. If *recursive* is ``True``, we will try to find *obj* within our
child nodes even if it is not a direct descendant of this
:class:`.Wikicode` object. If *obj* is not found, :exc:`ValueError` is
raised.
"""
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
else:
self._slice_replace(context, index, str(obj), "")
def matches(self, other):
"""Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, whitespace and markup is stripped and the first
letter's case is normalized. Typical usage is
``if template.name.matches("stub"): ...``.
"""
normalize = lambda s: (s[0].upper() + s[1:]).replace("_", " ") if s else s
this = normalize(self.strip_code().strip())
if isinstance(other, (str, bytes, Wikicode, Node)):
that = parse_anything(other).strip_code().strip()
return this == normalize(that)
for obj in other:
that = parse_anything(obj).strip_code().strip()
if this == normalize(that):
return True
return False
def ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
"""Iterate over nodes in our list matching certain conditions.
If *forcetype* is given, only nodes that are instances of this type (or
tuple of types) are yielded. Setting *recursive* to ``True`` will
iterate over all children and their descendants. ``RECURSE_OTHERS``
will only iterate over children that are not the instances of
*forcetype*. ``False`` will only iterate over immediate children.
``RECURSE_OTHERS`` can be used to iterate over all un-nested templates,
even if they are inside of HTML tags, like so:
>>> code = mwparserfromhell.parse("{{foo}}<b>{{foo|{{bar}}}}</b>")
>>> code.filter_templates(code.RECURSE_OTHERS)
["{{foo}}", "{{foo|{{bar}}}}"]
*matches* can be used to further restrict the nodes, either as a
function (taking a single :class:`.Node` and returning a boolean) or a
regular expression (matched against the node's string representation
with :func:`re.search`). If *matches* is a regex, the flags passed to
:func:`re.search` are :const:`re.IGNORECASE`, :const:`re.DOTALL`, and
:const:`re.UNICODE`, but custom flags can be specified by passing
*flags*.
"""
gen = self._indexed_ifilter(recursive, matches, flags, forcetype)
return (node for i, node in gen)
def filter(self, *args, **kwargs):
"""Return a list of nodes within our list matching certain conditions.
This is equivalent to calling :func:`list` on :meth:`ifilter`.
"""
return list(self.ifilter(*args, **kwargs))
def get_sections(self, levels=None, matches=None, flags=FLAGS, flat=False,
include_lead=None, include_headings=True):
"""Return a list of sections within the page.
Sections are returned as :class:`.Wikicode` objects with a shared node
list (implemented using :class:`.SmartList`) so that changes to
sections are reflected in the parent Wikicode object.
Each section contains all of its subsections, unless *flat* is
``True``. If *levels* is given, it should be a iterable of integers;
only sections whose heading levels are within it will be returned. If
*matches* is given, it should be either a function or a regex; only
sections whose headings match it (without the surrounding equal signs)
will be included. *flags* can be used to override the default regex
flags (see :meth:`ifilter`) if a regex *matches* is used.
If *include_lead* is ``True``, the first, lead section (without a
heading) will be included in the list; ``False`` will not include it;
the default will include it only if no specific *levels* were given. If
*include_headings* is ``True``, the section's beginning
:class:`.Heading` object will be included; otherwise, this is skipped.
"""
title_matcher = self._build_matcher(matches, flags)
matcher = lambda heading: (title_matcher(heading.title) and
(not levels or heading.level in levels))
iheadings = self._indexed_ifilter(recursive=False, forcetype=Heading)
sections = [] # Tuples of (index_of_first_node, section)
open_headings = [] # Tuples of (index, heading), where index and
# heading.level are both monotonically increasing
# Add the lead section if appropriate:
if include_lead or not (include_lead is not None or matches or levels):
itr = self._indexed_ifilter(recursive=False, forcetype=Heading)
try:
first = next(itr)[0]
sections.append((0, Wikicode(self.nodes[:first])))
except StopIteration: # No headings in page
sections.append((0, Wikicode(self.nodes[:])))
# Iterate over headings, adding sections to the list as they end:
for i, heading in iheadings:
if flat: # With flat, all sections close at the next heading
newly_closed, open_headings = open_headings, []
else: # Otherwise, figure out which sections have closed, if any
closed_start_index = len(open_headings)
for j, (start, last_heading) in enumerate(open_headings):
if heading.level <= last_heading.level:
closed_start_index = j
break
newly_closed = open_headings[closed_start_index:]
del open_headings[closed_start_index:]
for start, closed_heading in newly_closed:
if matcher(closed_heading):
sections.append((start, Wikicode(self.nodes[start:i])))
start = i if include_headings else (i + 1)
open_headings.append((start, heading))
# Add any remaining open headings to the list of sections:
for start, heading in open_headings:
if matcher(heading):
sections.append((start, Wikicode(self.nodes[start:])))
# Ensure that earlier sections are earlier in the returned list:
return [section for i, section in sorted(sections)]
def strip_code(self, normalize=True, collapse=True,
keep_template_params=False):
"""Return a rendered string without unprintable code such as templates.
The way a node is stripped is handled by the
:meth:`~.Node.__strip__` method of :class:`.Node` objects, which
generally return a subset of their nodes or ``None``. For example,
templates and tags are removed completely, links are stripped to just
their display part, headings are stripped to just their title.
If *normalize* is ``True``, various things may be done to strip code
further, such as converting HTML entities like ``Σ``, ``Σ``,
and ``Σ`` to ``Σ``. If *collapse* is ``True``, we will try to
remove excess whitespace as well (three or more newlines are converted
to two, for example). If *keep_template_params* is ``True``, then
template parameters will be preserved in the output (normally, they are
removed completely).
"""
kwargs = {
"normalize": normalize,
"collapse": collapse,
"keep_template_params": keep_template_params
}
nodes = []
for node in self.nodes:
stripped = node.__strip__(**kwargs)
if stripped:
nodes.append(str(stripped))
if collapse:
stripped = "".join(nodes).strip("\n")
while "\n\n\n" in stripped:
stripped = stripped.replace("\n\n\n", "\n\n")
return stripped
else:
return "".join(nodes)
def get_tree(self):
"""Return a hierarchical tree representation of the object.
The representation is a string makes the most sense printed. It is
built by calling :meth:`_get_tree` on the :class:`.Wikicode` object and
its children recursively. The end result may look something like the
following::
>>> text = "Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}"
>>> print(mwparserfromhell.parse(text).get_tree())
Lorem ipsum
{{
foo
| 1
= bar
| 2
= {{
baz
}}
| spam
= eggs
}}
"""
marker = object() # Random object we can find with certainty in a list
return "\n".join(self._get_tree(self, [], marker, 0))
Wikicode._build_filter_methods(
arguments=Argument, comments=Comment, external_links=ExternalLink,
headings=Heading, html_entities=HTMLEntity, tags=Tag, templates=Template,
text=Text, wikilinks=Wikilink)
| 44.945668 | 82 | 0.59785 |
import re
from itertools import chain
from .nodes import (Argument, Comment, ExternalLink, Heading, HTMLEntity,
Node, Tag, Template, Text, Wikilink)
from .smart_list.ListProxy import _ListProxy
from .string_mixin import StringMixIn
from .utils import parse_anything
__all__ = ["Wikicode"]
FLAGS = re.IGNORECASE | re.DOTALL | re.UNICODE
class Wikicode(StringMixIn):
RECURSE_OTHERS = 2
def __init__(self, nodes):
super().__init__()
self._nodes = nodes
def __unicode__(self):
return "".join([str(node) for node in self.nodes])
@staticmethod
def _get_children(node, contexts=False, restrict=None, parent=None):
yield (parent, node) if contexts else node
if restrict and isinstance(node, restrict):
return
for code in node.__children__():
for child in code.nodes:
sub = Wikicode._get_children(child, contexts, restrict, code)
yield from sub
@staticmethod
def _slice_replace(code, index, old, new):
nodes = [str(node) for node in code.get(index)]
substring = "".join(nodes).replace(old, new)
code.nodes[index] = parse_anything(substring).nodes
@staticmethod
def _build_matcher(matches, flags):
if matches:
if callable(matches):
return matches
return lambda obj: re.search(matches, str(obj), flags)
return lambda obj: True
def _indexed_ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
match = self._build_matcher(matches, flags)
if recursive:
restrict = forcetype if recursive == self.RECURSE_OTHERS else None
def getter(i, node):
for ch in self._get_children(node, restrict=restrict):
yield (i, ch)
inodes = chain(*(getter(i, n) for i, n in enumerate(self.nodes)))
else:
inodes = enumerate(self.nodes)
for i, node in inodes:
if (not forcetype or isinstance(node, forcetype)) and match(node):
yield (i, node)
def _is_child_wikicode(self, obj, recursive=True):
def deref(nodes):
if isinstance(nodes, _ListProxy):
return nodes._parent
return nodes
target = deref(obj.nodes)
if target is deref(self.nodes):
return True
if recursive:
todo = [self]
while todo:
code = todo.pop()
if target is deref(code.nodes):
return True
for node in code.nodes:
todo += list(node.__children__())
return False
def _do_strong_search(self, obj, recursive=True):
if isinstance(obj, Wikicode):
if not self._is_child_wikicode(obj, recursive):
raise ValueError(obj)
return obj, slice(0, len(obj.nodes))
if isinstance(obj, Node):
mkslice = lambda i: slice(i, i + 1)
if not recursive:
return self, mkslice(self.index(obj))
for node in self.nodes:
for context, child in self._get_children(node, contexts=True):
if obj is child:
if not context:
context = self
return context, mkslice(context.index(child))
raise ValueError(obj)
raise TypeError(obj)
def _do_weak_search(self, obj, recursive):
obj = parse_anything(obj)
if not obj or obj not in self:
raise ValueError(obj)
results = []
contexts = [self]
while contexts:
context = contexts.pop()
i = len(context.nodes) - 1
while i >= 0:
node = context.get(i)
if obj.get(-1) == node:
for j in range(-len(obj.nodes), -1):
if obj.get(j) != context.get(i + j + 1):
break
else:
i -= len(obj.nodes) - 1
index = slice(i, i + len(obj.nodes))
results.append((True, context, index))
elif recursive and obj in node:
contexts.extend(node.__children__())
i -= 1
if not results:
if not recursive:
raise ValueError(obj)
results.append((False, self, slice(0, len(self.nodes))))
return results
def _get_tree(self, code, lines, marker, indent):
def write(*args):
if lines and lines[-1] is marker:
lines.pop()
last = lines.pop()
lines.append(last + " ".join(args))
else:
lines.append(" " * 6 * indent + " ".join(args))
get = lambda code: self._get_tree(code, lines, marker, indent + 1)
mark = lambda: lines.append(marker)
for node in code.nodes:
node.__showtree__(write, get, mark)
return lines
@classmethod
def _build_filter_methods(cls, **meths):
doc = """Iterate over {0}.
This is equivalent to :meth:`{1}` with *forcetype* set to
:class:`~{2.__module__}.{2.__name__}`.
"""
make_ifilter = lambda ftype: (lambda self, *a, **kw:
self.ifilter(forcetype=ftype, *a, **kw))
make_filter = lambda ftype: (lambda self, *a, **kw:
self.filter(forcetype=ftype, *a, **kw))
for name, ftype in meths.items():
ifilter = make_ifilter(ftype)
filter = make_filter(ftype)
ifilter.__doc__ = doc.format(name, "ifilter", ftype)
filter.__doc__ = doc.format(name, "filter", ftype)
setattr(cls, "ifilter_" + name, ifilter)
setattr(cls, "filter_" + name, filter)
@property
def nodes(self):
return self._nodes
@nodes.setter
def nodes(self, value):
if not isinstance(value, list):
value = parse_anything(value).nodes
self._nodes = value
def get(self, index):
return self.nodes[index]
def set(self, index, value):
nodes = parse_anything(value).nodes
if len(nodes) > 1:
raise ValueError("Cannot coerce multiple nodes into one index")
if index >= len(self.nodes) or -1 * index > len(self.nodes):
raise IndexError("List assignment index out of range")
if nodes:
self.nodes[index] = nodes[0]
else:
self.nodes.pop(index)
def contains(self, obj):
if not isinstance(obj, (Node, Wikicode)):
return obj in self
try:
self._do_strong_search(obj, recursive=True)
except ValueError:
return False
return True
def index(self, obj, recursive=False):
strict = isinstance(obj, Node)
equivalent = (lambda o, n: o is n) if strict else (lambda o, n: o == n)
for i, node in enumerate(self.nodes):
if recursive:
for child in self._get_children(node):
if equivalent(obj, child):
return i
elif equivalent(obj, node):
return i
raise ValueError(obj)
def get_ancestors(self, obj):
def _get_ancestors(code, needle):
for node in code.nodes:
if node is needle:
return []
for code in node.__children__():
ancestors = _get_ancestors(code, needle)
if ancestors is not None:
return [node] + ancestors
if isinstance(obj, Wikicode):
obj = obj.get(0)
elif not isinstance(obj, Node):
raise ValueError(obj)
ancestors = _get_ancestors(self, obj)
if ancestors is None:
raise ValueError(obj)
return ancestors
def get_parent(self, obj):
ancestors = self.get_ancestors(obj)
return ancestors[-1] if ancestors else None
def insert(self, index, value):
nodes = parse_anything(value).nodes
for node in reversed(nodes):
self.nodes.insert(index, node)
def insert_before(self, obj, value, recursive=True):
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
context.insert(index.start, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
context.insert(index.start, value)
else:
obj = str(obj)
self._slice_replace(context, index, obj, str(value) + obj)
def insert_after(self, obj, value, recursive=True):
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
context.insert(index.stop, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
context.insert(index.stop, value)
else:
obj = str(obj)
self._slice_replace(context, index, obj, obj + str(value))
def replace(self, obj, value, recursive=True):
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
context.insert(index.start, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
context.insert(index.start, value)
else:
self._slice_replace(context, index, str(obj), str(value))
def append(self, value):
nodes = parse_anything(value).nodes
for node in nodes:
self.nodes.append(node)
def remove(self, obj, recursive=True):
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
else:
self._slice_replace(context, index, str(obj), "")
def matches(self, other):
normalize = lambda s: (s[0].upper() + s[1:]).replace("_", " ") if s else s
this = normalize(self.strip_code().strip())
if isinstance(other, (str, bytes, Wikicode, Node)):
that = parse_anything(other).strip_code().strip()
return this == normalize(that)
for obj in other:
that = parse_anything(obj).strip_code().strip()
if this == normalize(that):
return True
return False
def ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
gen = self._indexed_ifilter(recursive, matches, flags, forcetype)
return (node for i, node in gen)
def filter(self, *args, **kwargs):
return list(self.ifilter(*args, **kwargs))
def get_sections(self, levels=None, matches=None, flags=FLAGS, flat=False,
include_lead=None, include_headings=True):
title_matcher = self._build_matcher(matches, flags)
matcher = lambda heading: (title_matcher(heading.title) and
(not levels or heading.level in levels))
iheadings = self._indexed_ifilter(recursive=False, forcetype=Heading)
sections = []
open_headings = []
if include_lead or not (include_lead is not None or matches or levels):
itr = self._indexed_ifilter(recursive=False, forcetype=Heading)
try:
first = next(itr)[0]
sections.append((0, Wikicode(self.nodes[:first])))
except StopIteration:
sections.append((0, Wikicode(self.nodes[:])))
for i, heading in iheadings:
if flat:
newly_closed, open_headings = open_headings, []
else:
closed_start_index = len(open_headings)
for j, (start, last_heading) in enumerate(open_headings):
if heading.level <= last_heading.level:
closed_start_index = j
break
newly_closed = open_headings[closed_start_index:]
del open_headings[closed_start_index:]
for start, closed_heading in newly_closed:
if matcher(closed_heading):
sections.append((start, Wikicode(self.nodes[start:i])))
start = i if include_headings else (i + 1)
open_headings.append((start, heading))
for start, heading in open_headings:
if matcher(heading):
sections.append((start, Wikicode(self.nodes[start:])))
return [section for i, section in sorted(sections)]
def strip_code(self, normalize=True, collapse=True,
keep_template_params=False):
kwargs = {
"normalize": normalize,
"collapse": collapse,
"keep_template_params": keep_template_params
}
nodes = []
for node in self.nodes:
stripped = node.__strip__(**kwargs)
if stripped:
nodes.append(str(stripped))
if collapse:
stripped = "".join(nodes).strip("\n")
while "\n\n\n" in stripped:
stripped = stripped.replace("\n\n\n", "\n\n")
return stripped
else:
return "".join(nodes)
def get_tree(self):
marker = object()
return "\n".join(self._get_tree(self, [], marker, 0))
Wikicode._build_filter_methods(
arguments=Argument, comments=Comment, external_links=ExternalLink,
headings=Heading, html_entities=HTMLEntity, tags=Tag, templates=Template,
text=Text, wikilinks=Wikilink)
| true | true |
f72c26f1a5f1a4531136265e544d67ea32926477 | 539 | py | Python | vtstscripts-939/center.py | zybbigpy/VaspCZ | a652de66eec82e8618e71f0466296fabf66b5218 | [
"MIT"
] | 65 | 2019-09-16T12:00:58.000Z | 2022-03-17T04:43:05.000Z | vtstscripts-939/center.py | yizhiwoniu/VaspCZ | 44b890cf18d649c428c21e3f8fadc3222453d84d | [
"MIT"
] | null | null | null | vtstscripts-939/center.py | yizhiwoniu/VaspCZ | 44b890cf18d649c428c21e3f8fadc3222453d84d | [
"MIT"
] | 23 | 2019-09-16T12:16:57.000Z | 2021-11-18T15:57:38.000Z | #!/usr/bin/env python
import aselite
from sys import argv, exit
if len(argv) < 2 or len(argv) > 3 or '-h' in argv:
print 'usage: center.py FILE [DISTANCE]'
print ' centers the structure in the current box and'
print ' optionally adds DISTANCE amount of vacuum to FILE'
print
exit(0)
filename = argv[1]
if len(argv) == 3:
distance = float(argv[2])
else:
distance = None
atoms = aselite.read_any(filename)
if distance:
atoms.center(distance)
else:
atoms.center()
atoms.write(filename)
| 21.56 | 68 | 0.656772 |
import aselite
from sys import argv, exit
if len(argv) < 2 or len(argv) > 3 or '-h' in argv:
print 'usage: center.py FILE [DISTANCE]'
print ' centers the structure in the current box and'
print ' optionally adds DISTANCE amount of vacuum to FILE'
print
exit(0)
filename = argv[1]
if len(argv) == 3:
distance = float(argv[2])
else:
distance = None
atoms = aselite.read_any(filename)
if distance:
atoms.center(distance)
else:
atoms.center()
atoms.write(filename)
| false | true |
f72c27667d2dfd2d0ef541566592c06f430e047b | 147 | py | Python | scene/__init__.py | cloose/ray-tracer-challenge | 5e9dd56fb67c5cba47172986a963fc22a8cbcaa2 | [
"MIT"
] | null | null | null | scene/__init__.py | cloose/ray-tracer-challenge | 5e9dd56fb67c5cba47172986a963fc22a8cbcaa2 | [
"MIT"
] | null | null | null | scene/__init__.py | cloose/ray-tracer-challenge | 5e9dd56fb67c5cba47172986a963fc22a8cbcaa2 | [
"MIT"
] | null | null | null | from .camera import *
from .obj_file import *
from .obj_parser import *
from .ray_tracer import *
from .scene_parser import *
from .world import *
| 21 | 27 | 0.755102 | from .camera import *
from .obj_file import *
from .obj_parser import *
from .ray_tracer import *
from .scene_parser import *
from .world import *
| true | true |
f72c27de3695f8b7dc7c5ae95c8a39f24e92433e | 10,650 | py | Python | darling_ansible/python_venv/lib/python3.7/site-packages/oci/core/models/update_vnic_details.py | revnav/sandbox | f9c8422233d093b76821686b6c249417502cf61d | [
"Apache-2.0"
] | null | null | null | darling_ansible/python_venv/lib/python3.7/site-packages/oci/core/models/update_vnic_details.py | revnav/sandbox | f9c8422233d093b76821686b6c249417502cf61d | [
"Apache-2.0"
] | null | null | null | darling_ansible/python_venv/lib/python3.7/site-packages/oci/core/models/update_vnic_details.py | revnav/sandbox | f9c8422233d093b76821686b6c249417502cf61d | [
"Apache-2.0"
] | 1 | 2020-06-25T03:12:58.000Z | 2020-06-25T03:12:58.000Z | # coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class UpdateVnicDetails(object):
"""
UpdateVnicDetails model.
"""
def __init__(self, **kwargs):
"""
Initializes a new UpdateVnicDetails object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param defined_tags:
The value to assign to the defined_tags property of this UpdateVnicDetails.
:type defined_tags: dict(str, dict(str, object))
:param display_name:
The value to assign to the display_name property of this UpdateVnicDetails.
:type display_name: str
:param freeform_tags:
The value to assign to the freeform_tags property of this UpdateVnicDetails.
:type freeform_tags: dict(str, str)
:param hostname_label:
The value to assign to the hostname_label property of this UpdateVnicDetails.
:type hostname_label: str
:param nsg_ids:
The value to assign to the nsg_ids property of this UpdateVnicDetails.
:type nsg_ids: list[str]
:param skip_source_dest_check:
The value to assign to the skip_source_dest_check property of this UpdateVnicDetails.
:type skip_source_dest_check: bool
"""
self.swagger_types = {
'defined_tags': 'dict(str, dict(str, object))',
'display_name': 'str',
'freeform_tags': 'dict(str, str)',
'hostname_label': 'str',
'nsg_ids': 'list[str]',
'skip_source_dest_check': 'bool'
}
self.attribute_map = {
'defined_tags': 'definedTags',
'display_name': 'displayName',
'freeform_tags': 'freeformTags',
'hostname_label': 'hostnameLabel',
'nsg_ids': 'nsgIds',
'skip_source_dest_check': 'skipSourceDestCheck'
}
self._defined_tags = None
self._display_name = None
self._freeform_tags = None
self._hostname_label = None
self._nsg_ids = None
self._skip_source_dest_check = None
@property
def defined_tags(self):
"""
Gets the defined_tags of this UpdateVnicDetails.
Defined tags for this resource. Each key is predefined and scoped to a
namespace. For more information, see `Resource Tags`__.
Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The defined_tags of this UpdateVnicDetails.
:rtype: dict(str, dict(str, object))
"""
return self._defined_tags
@defined_tags.setter
def defined_tags(self, defined_tags):
"""
Sets the defined_tags of this UpdateVnicDetails.
Defined tags for this resource. Each key is predefined and scoped to a
namespace. For more information, see `Resource Tags`__.
Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param defined_tags: The defined_tags of this UpdateVnicDetails.
:type: dict(str, dict(str, object))
"""
self._defined_tags = defined_tags
@property
def display_name(self):
"""
Gets the display_name of this UpdateVnicDetails.
A user-friendly name. Does not have to be unique, and it's changeable.
Avoid entering confidential information.
:return: The display_name of this UpdateVnicDetails.
:rtype: str
"""
return self._display_name
@display_name.setter
def display_name(self, display_name):
"""
Sets the display_name of this UpdateVnicDetails.
A user-friendly name. Does not have to be unique, and it's changeable.
Avoid entering confidential information.
:param display_name: The display_name of this UpdateVnicDetails.
:type: str
"""
self._display_name = display_name
@property
def freeform_tags(self):
"""
Gets the freeform_tags of this UpdateVnicDetails.
Free-form tags for this resource. Each tag is a simple key-value pair with no
predefined name, type, or namespace. For more information, see `Resource Tags`__.
Example: `{\"Department\": \"Finance\"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The freeform_tags of this UpdateVnicDetails.
:rtype: dict(str, str)
"""
return self._freeform_tags
@freeform_tags.setter
def freeform_tags(self, freeform_tags):
"""
Sets the freeform_tags of this UpdateVnicDetails.
Free-form tags for this resource. Each tag is a simple key-value pair with no
predefined name, type, or namespace. For more information, see `Resource Tags`__.
Example: `{\"Department\": \"Finance\"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param freeform_tags: The freeform_tags of this UpdateVnicDetails.
:type: dict(str, str)
"""
self._freeform_tags = freeform_tags
@property
def hostname_label(self):
"""
Gets the hostname_label of this UpdateVnicDetails.
The hostname for the VNIC's primary private IP. Used for DNS. The value is the hostname
portion of the primary private IP's fully qualified domain name (FQDN)
(for example, `bminstance-1` in FQDN `bminstance-1.subnet123.vcn1.oraclevcn.com`).
Must be unique across all VNICs in the subnet and comply with
`RFC 952`__ and
`RFC 1123`__.
The value appears in the :class:`Vnic` object and also the
:class:`PrivateIp` object returned by
:func:`list_private_ips` and
:func:`get_private_ip`.
For more information, see
`DNS in Your Virtual Cloud Network`__.
__ https://tools.ietf.org/html/rfc952
__ https://tools.ietf.org/html/rfc1123
__ https://docs.cloud.oracle.com/Content/Network/Concepts/dns.htm
:return: The hostname_label of this UpdateVnicDetails.
:rtype: str
"""
return self._hostname_label
@hostname_label.setter
def hostname_label(self, hostname_label):
"""
Sets the hostname_label of this UpdateVnicDetails.
The hostname for the VNIC's primary private IP. Used for DNS. The value is the hostname
portion of the primary private IP's fully qualified domain name (FQDN)
(for example, `bminstance-1` in FQDN `bminstance-1.subnet123.vcn1.oraclevcn.com`).
Must be unique across all VNICs in the subnet and comply with
`RFC 952`__ and
`RFC 1123`__.
The value appears in the :class:`Vnic` object and also the
:class:`PrivateIp` object returned by
:func:`list_private_ips` and
:func:`get_private_ip`.
For more information, see
`DNS in Your Virtual Cloud Network`__.
__ https://tools.ietf.org/html/rfc952
__ https://tools.ietf.org/html/rfc1123
__ https://docs.cloud.oracle.com/Content/Network/Concepts/dns.htm
:param hostname_label: The hostname_label of this UpdateVnicDetails.
:type: str
"""
self._hostname_label = hostname_label
@property
def nsg_ids(self):
"""
Gets the nsg_ids of this UpdateVnicDetails.
A list of the OCIDs of the network security groups (NSGs) to add the VNIC to. Setting this as
an empty array removes the VNIC from all network security groups.
For more information about NSGs, see
:class:`NetworkSecurityGroup`.
:return: The nsg_ids of this UpdateVnicDetails.
:rtype: list[str]
"""
return self._nsg_ids
@nsg_ids.setter
def nsg_ids(self, nsg_ids):
"""
Sets the nsg_ids of this UpdateVnicDetails.
A list of the OCIDs of the network security groups (NSGs) to add the VNIC to. Setting this as
an empty array removes the VNIC from all network security groups.
For more information about NSGs, see
:class:`NetworkSecurityGroup`.
:param nsg_ids: The nsg_ids of this UpdateVnicDetails.
:type: list[str]
"""
self._nsg_ids = nsg_ids
@property
def skip_source_dest_check(self):
"""
Gets the skip_source_dest_check of this UpdateVnicDetails.
Whether the source/destination check is disabled on the VNIC.
Defaults to `false`, which means the check is performed.
For information about why you would skip the source/destination check, see
`Using a Private IP as a Route Target`__.
Example: `true`
__ https://docs.cloud.oracle.com/Content/Network/Tasks/managingroutetables.htm#privateip
:return: The skip_source_dest_check of this UpdateVnicDetails.
:rtype: bool
"""
return self._skip_source_dest_check
@skip_source_dest_check.setter
def skip_source_dest_check(self, skip_source_dest_check):
"""
Sets the skip_source_dest_check of this UpdateVnicDetails.
Whether the source/destination check is disabled on the VNIC.
Defaults to `false`, which means the check is performed.
For information about why you would skip the source/destination check, see
`Using a Private IP as a Route Target`__.
Example: `true`
__ https://docs.cloud.oracle.com/Content/Network/Tasks/managingroutetables.htm#privateip
:param skip_source_dest_check: The skip_source_dest_check of this UpdateVnicDetails.
:type: bool
"""
self._skip_source_dest_check = skip_source_dest_check
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| 35.264901 | 245 | 0.65615 |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class UpdateVnicDetails(object):
def __init__(self, **kwargs):
self.swagger_types = {
'defined_tags': 'dict(str, dict(str, object))',
'display_name': 'str',
'freeform_tags': 'dict(str, str)',
'hostname_label': 'str',
'nsg_ids': 'list[str]',
'skip_source_dest_check': 'bool'
}
self.attribute_map = {
'defined_tags': 'definedTags',
'display_name': 'displayName',
'freeform_tags': 'freeformTags',
'hostname_label': 'hostnameLabel',
'nsg_ids': 'nsgIds',
'skip_source_dest_check': 'skipSourceDestCheck'
}
self._defined_tags = None
self._display_name = None
self._freeform_tags = None
self._hostname_label = None
self._nsg_ids = None
self._skip_source_dest_check = None
@property
def defined_tags(self):
return self._defined_tags
@defined_tags.setter
def defined_tags(self, defined_tags):
self._defined_tags = defined_tags
@property
def display_name(self):
return self._display_name
@display_name.setter
def display_name(self, display_name):
self._display_name = display_name
@property
def freeform_tags(self):
return self._freeform_tags
@freeform_tags.setter
def freeform_tags(self, freeform_tags):
self._freeform_tags = freeform_tags
@property
def hostname_label(self):
return self._hostname_label
@hostname_label.setter
def hostname_label(self, hostname_label):
self._hostname_label = hostname_label
@property
def nsg_ids(self):
return self._nsg_ids
@nsg_ids.setter
def nsg_ids(self, nsg_ids):
self._nsg_ids = nsg_ids
@property
def skip_source_dest_check(self):
return self._skip_source_dest_check
@skip_source_dest_check.setter
def skip_source_dest_check(self, skip_source_dest_check):
self._skip_source_dest_check = skip_source_dest_check
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f72c287955fbff99748da09097b2149ee342155e | 2,564 | py | Python | smartrecruiters_python_client/models/json_patch.py | roksela/smartrecruiters-python-client | 6d0849d173a3d6718b5f0769098f4c76857f637d | [
"MIT"
] | 5 | 2018-03-27T08:20:13.000Z | 2022-03-30T06:23:38.000Z | smartrecruiters_python_client/models/json_patch.py | roksela/smartrecruiters-python-client | 6d0849d173a3d6718b5f0769098f4c76857f637d | [
"MIT"
] | null | null | null | smartrecruiters_python_client/models/json_patch.py | roksela/smartrecruiters-python-client | 6d0849d173a3d6718b5f0769098f4c76857f637d | [
"MIT"
] | 2 | 2018-12-05T04:48:37.000Z | 2020-12-17T12:12:12.000Z | # coding: utf-8
"""
Unofficial python library for the SmartRecruiters API
The SmartRecruiters API provides a platform to integrate services or applications, build apps and create fully customizable career sites. It exposes SmartRecruiters functionality and allows to connect and build software enhancing it.
OpenAPI spec version: 1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class JSONPatch(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
JSONPatch - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
}
self.attribute_map = {
}
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, JSONPatch):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| 27.276596 | 237 | 0.543682 |
from pprint import pformat
from six import iteritems
import re
class JSONPatch(object):
def __init__(self):
self.swagger_types = {
}
self.attribute_map = {
}
def to_dict(self):
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
return pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, JSONPatch):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f72c2931d18a600dc4eaf9f2b95c5f5248adbea1 | 900 | py | Python | transmissionServer.py | crate19970523/yoloKnifeCallPolice- | 47b716dbacdd0d31282d13e0ec957711b3f967ca | [
"MIT"
] | null | null | null | transmissionServer.py | crate19970523/yoloKnifeCallPolice- | 47b716dbacdd0d31282d13e0ec957711b3f967ca | [
"MIT"
] | null | null | null | transmissionServer.py | crate19970523/yoloKnifeCallPolice- | 47b716dbacdd0d31282d13e0ec957711b3f967ca | [
"MIT"
] | null | null | null | #coding:utf-8
from flask import request, Flask
import time
import os
app = Flask(__name__)
@app.route("/", methods=['POST'])
def get_frame():
start_time = time.time()
upload_file = request.files['file']
old_file_name = upload_file.filename
if upload_file:
file_path = os.path.join('./imgtest/', old_file_name) #Server端的存放位置
upload_file.save(file_path)
print ("success")
if not os.path.isfile('imgtest/ltuschool.jpg'):
print('有近來喔')
os.rename('./imgtest/ltu.jpg','./imgtest/ltuschool.jpg')
print('file saved to %s' % file_path)
duration = time.time() - start_time
print('duration:[%.0fms]' % (duration*1000))
return 'success'
else:
return 'failed'
def transmission():
app.run("192.168.43.179", port=5000) #Server端的IP以及port
if __name__ == "__main__":
transmission() | 31.034483 | 77 | 0.622222 |
from flask import request, Flask
import time
import os
app = Flask(__name__)
@app.route("/", methods=['POST'])
def get_frame():
start_time = time.time()
upload_file = request.files['file']
old_file_name = upload_file.filename
if upload_file:
file_path = os.path.join('./imgtest/', old_file_name)
upload_file.save(file_path)
print ("success")
if not os.path.isfile('imgtest/ltuschool.jpg'):
print('有近來喔')
os.rename('./imgtest/ltu.jpg','./imgtest/ltuschool.jpg')
print('file saved to %s' % file_path)
duration = time.time() - start_time
print('duration:[%.0fms]' % (duration*1000))
return 'success'
else:
return 'failed'
def transmission():
app.run("192.168.43.179", port=5000)
if __name__ == "__main__":
transmission() | true | true |
f72c298f250b50e48003137adac62548fe42bbfa | 721 | py | Python | tests/test_split_audio_file.py | greenkeytech/greenkey-asrtoolkit | f9a5990ee5c67b85dd8ff763777c986b03252ee5 | [
"Apache-2.0"
] | 31 | 2019-08-03T08:42:37.000Z | 2022-01-12T18:00:11.000Z | tests/test_split_audio_file.py | greenkeytech/greenkey-asrtoolkit | f9a5990ee5c67b85dd8ff763777c986b03252ee5 | [
"Apache-2.0"
] | 28 | 2019-07-29T17:58:17.000Z | 2021-08-20T14:30:25.000Z | tests/test_split_audio_file.py | greenkeytech/greenkey-asrtoolkit | f9a5990ee5c67b85dd8ff763777c986b03252ee5 | [
"Apache-2.0"
] | 12 | 2019-07-29T13:16:41.000Z | 2022-02-20T21:19:35.000Z | #!/usr/bin/env python
"""
Test audio file splitter
"""
import os
from asrtoolkit.split_audio_file import split_audio_file
from utils import get_test_dir
test_dir = get_test_dir(__file__)
def test_split_audio_file():
"""
Test audio file splitter
"""
split_audio_file(
f"{test_dir}/small-test-file.mp3",
f"{test_dir}/small-test-file.stm",
f"{test_dir}/split",
)
assert set(os.listdir(f"{test_dir}/split")) == {
"small_test_file_seg_00001.stm",
"small_test_file_seg_00000.mp3",
"small_test_file_seg_00001.mp3",
"small_test_file_seg_00000.stm",
}
if __name__ == "__main__":
import sys
import pytest
pytest.main(sys.argv)
| 20.027778 | 56 | 0.660194 |
import os
from asrtoolkit.split_audio_file import split_audio_file
from utils import get_test_dir
test_dir = get_test_dir(__file__)
def test_split_audio_file():
split_audio_file(
f"{test_dir}/small-test-file.mp3",
f"{test_dir}/small-test-file.stm",
f"{test_dir}/split",
)
assert set(os.listdir(f"{test_dir}/split")) == {
"small_test_file_seg_00001.stm",
"small_test_file_seg_00000.mp3",
"small_test_file_seg_00001.mp3",
"small_test_file_seg_00000.stm",
}
if __name__ == "__main__":
import sys
import pytest
pytest.main(sys.argv)
| true | true |
f72c29994545a8752c8d6412f035b921d01d390f | 4,755 | py | Python | tests/test_parvec.py | DaveMcEwan/dmppl | 68e8a121d4591360080cd40121add1796ae48a1b | [
"MIT"
] | 1 | 2020-05-05T19:46:43.000Z | 2020-05-05T19:46:43.000Z | tests/test_parvec.py | DaveMcEwan/dmppl | 68e8a121d4591360080cd40121add1796ae48a1b | [
"MIT"
] | null | null | null | tests/test_parvec.py | DaveMcEwan/dmppl | 68e8a121d4591360080cd40121add1796ae48a1b | [
"MIT"
] | null | null | null | from dmppl.scripts.parvec import entryPoint
from dmppl.base import rdTxt
from dmppl.test import runEntryPoint
import os
import tempfile
import shutil
import sys
import unittest
class Test_Parvec(unittest.TestCase): # {{{
def setUp(self):
# Different PRNGs between CPython versions.
# Check against golden for 3.5, 3.6, 3.7, but for other versions just check
# the same thing is generated twice using the same seed.
self.knownPrng = sys.version_info[:2] in [(3, 5), (3, 6), (3, 7)]
self.tstDir = tempfile.mkdtemp()
self.yml0 = '''\
PP_CPU$_$:
- [0, 1, 2]
- ["LSU", "ALU"]
- ["SS", "TT", "FF"]
PB_L$CACHE_EVICT:
- [1, 2]
- {pre-name: foo, post-value: bar}
- ["PERIODIC", "ROUNDROBIN"]
PI_FIFO$_LAYOUT:
- 0..10..2
- ["LINE", "CIRC"]
PL_COUNTER$_THRESH$:
- pre-value: "('d"
post-value: ");"
pre-name: "#blah "
- 0..2
- 0..5
- 100..333..5
'''
self.fnamei0 = os.path.join(self.tstDir, "tst0.yml")
with open(self.fnamei0, 'w') as fd:
fd.write(self.yml0)
self.goldenOut0 = '''\
// seed: 0
fooPB_L1CACHE_EVICT ROUNDROBINbar
fooPB_L2CACHE_EVICT ROUNDROBINbar
`define PI_FIFO0_LAYOUT CIRC
`define PI_FIFO2_LAYOUT LINE
`define PI_FIFO4_LAYOUT LINE
`define PI_FIFO6_LAYOUT LINE
`define PI_FIFO8_LAYOUT LINE
#blah PL_COUNTER0_THRESH0 ('d250);
#blah PL_COUNTER0_THRESH1 ('d210);
#blah PL_COUNTER0_THRESH2 ('d285);
#blah PL_COUNTER0_THRESH3 ('d165);
#blah PL_COUNTER0_THRESH4 ('d260);
#blah PL_COUNTER1_THRESH0 ('d140);
#blah PL_COUNTER1_THRESH1 ('d190);
#blah PL_COUNTER1_THRESH2 ('d140);
#blah PL_COUNTER1_THRESH3 ('d130);
#blah PL_COUNTER1_THRESH4 ('d295);
`define PP_CPU0_ALU SS
`define PP_CPU0_LSU TT
`define PP_CPU1_ALU TT
`define PP_CPU1_LSU TT
`define PP_CPU2_ALU FF
`define PP_CPU2_LSU SS
'''
self.yml1 = '''\
WEALTH_$:
- [Alice, Bob]
- 0..1000
GOODNESS_$_$:
- [Alice, Bob, Charlie, Eve]
- [Black, White, Gray]
- [lovely, evil]
'''
self.fnamei1 = os.path.join(self.tstDir, "tst1.yml")
with open(self.fnamei1, 'w') as fd:
fd.write(self.yml1)
self.goldenOut1 = '''\
// seed: 123
`define GOODNESS_Alice_Black evil
`define GOODNESS_Alice_Gray lovely
`define GOODNESS_Alice_White evil
`define GOODNESS_Bob_Black lovely
`define GOODNESS_Bob_Gray lovely
`define GOODNESS_Bob_White evil
`define GOODNESS_Charlie_Black evil
`define GOODNESS_Charlie_Gray lovely
`define GOODNESS_Charlie_White lovely
`define GOODNESS_Eve_Black lovely
`define GOODNESS_Eve_Gray evil
`define GOODNESS_Eve_White evil
`define WEALTH_Alice 138
`define WEALTH_Bob 345
'''
def tearDown(self):
shutil.rmtree(self.tstDir)
def test_Basic0(self):
self.maxDiff = None
if self.knownPrng:
cmd = "parvec --seed 123 %s" % (self.fnamei1)
stdout, stderr = runEntryPoint(cmd, entryPoint)
self.assertEqual(stderr, "")
self.assertEqual(self.goldenOut1, stdout)
else:
pass
def test_StdIO(self):
self.maxDiff = None
if self.knownPrng:
cmd = "parvec --seed 0"
stdout, stderr = runEntryPoint(cmd, entryPoint, stdinput=self.yml0)
self.assertEqual(stderr, "")
self.assertEqual(self.goldenOut0, stdout)
else:
pass
def test_Features0(self):
self.maxDiff = None
if self.knownPrng:
fnameo0 = self.fnamei0 + ".out"
cmd = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0)
stdout, stderr = runEntryPoint(cmd, entryPoint)
self.assertEqual(stderr, "")
self.assertEqual(stdout, "")
resultTxt = rdTxt(os.path.join(self.tstDir, fnameo0))
self.assertEqual(self.goldenOut0, resultTxt)
else:
fnameo0_A = self.fnamei0 + ".outA"
fnameo0_B = self.fnamei0 + ".outB"
cmdA = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0_A)
cmdB = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0_B)
stdoutA, stderrA = runEntryPoint(cmdA, entryPoint)
#stdoutA, stderrA = runEntryPoint(cmdA, entryPoint, redirect=False)
self.assertEqual(stderrA, "")
self.assertEqual(stdoutA, "")
stdoutB, stderrB = runEntryPoint(cmdB, entryPoint)
#stdoutB, stderrB = runEntryPoint(cmdB, entryPoint, redirect=False)
self.assertEqual(stderrB, "")
self.assertEqual(stdoutB, "")
resultTxtA = rdTxt(os.path.join(self.tstDir, fnameo0_A))
resultTxtB = rdTxt(os.path.join(self.tstDir, fnameo0_B))
self.assertEqual(resultTxtA, resultTxtB)
# }}} class Test_Parvec
| 30.876623 | 83 | 0.63428 | from dmppl.scripts.parvec import entryPoint
from dmppl.base import rdTxt
from dmppl.test import runEntryPoint
import os
import tempfile
import shutil
import sys
import unittest
class Test_Parvec(unittest.TestCase):
def setUp(self):
self.knownPrng = sys.version_info[:2] in [(3, 5), (3, 6), (3, 7)]
self.tstDir = tempfile.mkdtemp()
self.yml0 = '''\
PP_CPU$_$:
- [0, 1, 2]
- ["LSU", "ALU"]
- ["SS", "TT", "FF"]
PB_L$CACHE_EVICT:
- [1, 2]
- {pre-name: foo, post-value: bar}
- ["PERIODIC", "ROUNDROBIN"]
PI_FIFO$_LAYOUT:
- 0..10..2
- ["LINE", "CIRC"]
PL_COUNTER$_THRESH$:
- pre-value: "('d"
post-value: ");"
pre-name: "#blah "
- 0..2
- 0..5
- 100..333..5
'''
self.fnamei0 = os.path.join(self.tstDir, "tst0.yml")
with open(self.fnamei0, 'w') as fd:
fd.write(self.yml0)
self.goldenOut0 = '''\
// seed: 0
fooPB_L1CACHE_EVICT ROUNDROBINbar
fooPB_L2CACHE_EVICT ROUNDROBINbar
`define PI_FIFO0_LAYOUT CIRC
`define PI_FIFO2_LAYOUT LINE
`define PI_FIFO4_LAYOUT LINE
`define PI_FIFO6_LAYOUT LINE
`define PI_FIFO8_LAYOUT LINE
#blah PL_COUNTER0_THRESH0 ('d250);
#blah PL_COUNTER0_THRESH1 ('d210);
#blah PL_COUNTER0_THRESH2 ('d285);
#blah PL_COUNTER0_THRESH3 ('d165);
#blah PL_COUNTER0_THRESH4 ('d260);
#blah PL_COUNTER1_THRESH0 ('d140);
#blah PL_COUNTER1_THRESH1 ('d190);
#blah PL_COUNTER1_THRESH2 ('d140);
#blah PL_COUNTER1_THRESH3 ('d130);
#blah PL_COUNTER1_THRESH4 ('d295);
`define PP_CPU0_ALU SS
`define PP_CPU0_LSU TT
`define PP_CPU1_ALU TT
`define PP_CPU1_LSU TT
`define PP_CPU2_ALU FF
`define PP_CPU2_LSU SS
'''
self.yml1 = '''\
WEALTH_$:
- [Alice, Bob]
- 0..1000
GOODNESS_$_$:
- [Alice, Bob, Charlie, Eve]
- [Black, White, Gray]
- [lovely, evil]
'''
self.fnamei1 = os.path.join(self.tstDir, "tst1.yml")
with open(self.fnamei1, 'w') as fd:
fd.write(self.yml1)
self.goldenOut1 = '''\
// seed: 123
`define GOODNESS_Alice_Black evil
`define GOODNESS_Alice_Gray lovely
`define GOODNESS_Alice_White evil
`define GOODNESS_Bob_Black lovely
`define GOODNESS_Bob_Gray lovely
`define GOODNESS_Bob_White evil
`define GOODNESS_Charlie_Black evil
`define GOODNESS_Charlie_Gray lovely
`define GOODNESS_Charlie_White lovely
`define GOODNESS_Eve_Black lovely
`define GOODNESS_Eve_Gray evil
`define GOODNESS_Eve_White evil
`define WEALTH_Alice 138
`define WEALTH_Bob 345
'''
def tearDown(self):
shutil.rmtree(self.tstDir)
def test_Basic0(self):
self.maxDiff = None
if self.knownPrng:
cmd = "parvec --seed 123 %s" % (self.fnamei1)
stdout, stderr = runEntryPoint(cmd, entryPoint)
self.assertEqual(stderr, "")
self.assertEqual(self.goldenOut1, stdout)
else:
pass
def test_StdIO(self):
self.maxDiff = None
if self.knownPrng:
cmd = "parvec --seed 0"
stdout, stderr = runEntryPoint(cmd, entryPoint, stdinput=self.yml0)
self.assertEqual(stderr, "")
self.assertEqual(self.goldenOut0, stdout)
else:
pass
def test_Features0(self):
self.maxDiff = None
if self.knownPrng:
fnameo0 = self.fnamei0 + ".out"
cmd = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0)
stdout, stderr = runEntryPoint(cmd, entryPoint)
self.assertEqual(stderr, "")
self.assertEqual(stdout, "")
resultTxt = rdTxt(os.path.join(self.tstDir, fnameo0))
self.assertEqual(self.goldenOut0, resultTxt)
else:
fnameo0_A = self.fnamei0 + ".outA"
fnameo0_B = self.fnamei0 + ".outB"
cmdA = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0_A)
cmdB = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0_B)
stdoutA, stderrA = runEntryPoint(cmdA, entryPoint)
#stdoutA, stderrA = runEntryPoint(cmdA, entryPoint, redirect=False)
self.assertEqual(stderrA, "")
self.assertEqual(stdoutA, "")
stdoutB, stderrB = runEntryPoint(cmdB, entryPoint)
#stdoutB, stderrB = runEntryPoint(cmdB, entryPoint, redirect=False)
self.assertEqual(stderrB, "")
self.assertEqual(stdoutB, "")
resultTxtA = rdTxt(os.path.join(self.tstDir, fnameo0_A))
resultTxtB = rdTxt(os.path.join(self.tstDir, fnameo0_B))
self.assertEqual(resultTxtA, resultTxtB)
# }}} class Test_Parvec
| true | true |
f72c29c259a32921c65201a24cdc494eaddc5c96 | 3,974 | gyp | Python | gyp/freetype.gyp | Frankie-666/color-emoji.skia | f1634a9952086155b9069d49ab91f1fa43b5ec6a | [
"BSD-3-Clause"
] | 1 | 2018-06-18T03:20:08.000Z | 2018-06-18T03:20:08.000Z | gyp/freetype.gyp | Frankie-666/color-emoji.skia | f1634a9952086155b9069d49ab91f1fa43b5ec6a | [
"BSD-3-Clause"
] | null | null | null | gyp/freetype.gyp | Frankie-666/color-emoji.skia | f1634a9952086155b9069d49ab91f1fa43b5ec6a | [
"BSD-3-Clause"
] | null | null | null | {
'targets': [
{
'target_name': 'freetype',
'type': 'static_library',
'standalone_static_library': 1,
'sources': [
# base components (required)
'../third_party/externals/freetype/src/base/ftsystem.c',
'../third_party/externals/freetype/src/base/ftinit.c',
'../third_party/externals/freetype/src/base/ftdebug.c',
'../third_party/externals/freetype/src/base/ftbase.c',
'../third_party/externals/freetype/src/base/ftbbox.c', # recommended, see <freetype/ftbbox.h>
'../third_party/externals/freetype/src/base/ftglyph.c', # recommended, see <freetype/ftglyph.h>
'../third_party/externals/freetype/src/base/ftbitmap.c', # optional, see <freetype/ftbitmap.h>
'../third_party/externals/freetype/src/base/ftfstype.c', # optional
'../third_party/externals/freetype/src/base/ftgasp.c', # optional, see <freetype/ftgasp.h>
'../third_party/externals/freetype/src/base/ftlcdfil.c', # optional, see <freetype/ftlcdfil.h>
'../third_party/externals/freetype/src/base/ftmm.c', # optional, see <freetype/ftmm.h>
'../third_party/externals/freetype/src/base/ftpatent.c', # optional
'../third_party/externals/freetype/src/base/ftstroke.c', # optional, see <freetype/ftstroke.h>
'../third_party/externals/freetype/src/base/ftsynth.c', # optional, see <freetype/ftsynth.h>
'../third_party/externals/freetype/src/base/fttype1.c', # optional, see <freetype/t1tables.h>
'../third_party/externals/freetype/src/base/ftwinfnt.c', # optional, see <freetype/ftwinfnt.h>
'../third_party/externals/freetype/src/base/ftxf86.c', # optional, see <freetype/ftxf86.h>
# font drivers (optional; at least one is needed)
'../third_party/externals/freetype/src/cff/cff.c', # CFF/OpenType font driver
'../third_party/externals/freetype/src/sfnt/sfnt.c', # SFNT files support (TrueType & OpenType)
'../third_party/externals/freetype/src/truetype/truetype.c', # TrueType font driver
# rasterizers (optional; at least one is needed for vector formats)
'../third_party/externals/freetype/src/raster/raster.c', # monochrome rasterizer
'../third_party/externals/freetype/src/smooth/smooth.c', # anti-aliasing rasterizer
# auxiliary modules (optional)
'../third_party/externals/freetype/src/autofit/autofit.c', # auto hinting module
'../third_party/externals/freetype/src/psaux/psaux.c', # PostScript Type 1 parsing
'../third_party/externals/freetype/src/pshinter/pshinter.c', # PS hinting module
'../third_party/externals/freetype/src/psnames/psnames.c', # PostScript glyph names support
],
'include_dirs': [
'../third_party/externals/freetype/internal',
'../third_party/externals/freetype/builds',
'../third_party/externals/freetype/include',
'../third_party/externals/freetype',
],
'cflags': [
'-DFT2_BUILD_LIBRARY',
],
'direct_dependent_settings': {
'include_dirs': [
'../third_party/externals/freetype/include',
],
},
'conditions': [
[ 'skia_os == "mac"', {
'sources': [
'../third_party/externals/freetype/src/base/ftmac.c', # only on the Macintosh
],
}],
[ 'skia_os == "android"', {
# These flags are used by the Android OS. They are probably overkill
# for Skia, but we add them for consistency.
'cflags': [
'-W',
'-Wall',
'-fPIC',
'-DPIC',
'-DDARWIN_NO_CARBON',
'-DFT2_BUILD_LIBRARY',
'-O2',
],
}],
],
},
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| 45.678161 | 111 | 0.606945 | {
'targets': [
{
'target_name': 'freetype',
'type': 'static_library',
'standalone_static_library': 1,
'sources': [
'../third_party/externals/freetype/src/base/ftsystem.c',
'../third_party/externals/freetype/src/base/ftinit.c',
'../third_party/externals/freetype/src/base/ftdebug.c',
'../third_party/externals/freetype/src/base/ftbase.c',
'../third_party/externals/freetype/src/base/ftbbox.c',
'../third_party/externals/freetype/src/base/ftglyph.c',
'../third_party/externals/freetype/src/base/ftbitmap.c',
'../third_party/externals/freetype/src/base/ftfstype.c',
'../third_party/externals/freetype/src/base/ftgasp.c',
'../third_party/externals/freetype/src/base/ftlcdfil.c',
'../third_party/externals/freetype/src/base/ftmm.c',
'../third_party/externals/freetype/src/base/ftpatent.c',
'../third_party/externals/freetype/src/base/ftstroke.c',
'../third_party/externals/freetype/src/base/ftsynth.c',
'../third_party/externals/freetype/src/base/fttype1.c',
'../third_party/externals/freetype/src/base/ftwinfnt.c',
'../third_party/externals/freetype/src/base/ftxf86.c',
'../third_party/externals/freetype/src/cff/cff.c',
'../third_party/externals/freetype/src/sfnt/sfnt.c',
'../third_party/externals/freetype/src/truetype/truetype.c',
'../third_party/externals/freetype/src/raster/raster.c',
'../third_party/externals/freetype/src/smooth/smooth.c',
'../third_party/externals/freetype/src/autofit/autofit.c',
'../third_party/externals/freetype/src/psaux/psaux.c',
'../third_party/externals/freetype/src/pshinter/pshinter.c',
'../third_party/externals/freetype/src/psnames/psnames.c',
],
'include_dirs': [
'../third_party/externals/freetype/internal',
'../third_party/externals/freetype/builds',
'../third_party/externals/freetype/include',
'../third_party/externals/freetype',
],
'cflags': [
'-DFT2_BUILD_LIBRARY',
],
'direct_dependent_settings': {
'include_dirs': [
'../third_party/externals/freetype/include',
],
},
'conditions': [
[ 'skia_os == "mac"', {
'sources': [
'../third_party/externals/freetype/src/base/ftmac.c',
],
}],
[ 'skia_os == "android"', {
'cflags': [
'-W',
'-Wall',
'-fPIC',
'-DPIC',
'-DDARWIN_NO_CARBON',
'-DFT2_BUILD_LIBRARY',
'-O2',
],
}],
],
},
],
}
| true | true |
f72c2a8a8a6c7d963cd917f661bb29b5ba4d5351 | 12,831 | py | Python | utils/data_utils.py | joshchang1112/gcnn-survey-paper | 591af8d6c4374378831cab2cdec79575e2540d79 | [
"Apache-2.0"
] | 155 | 2019-12-18T19:01:02.000Z | 2022-03-12T16:34:06.000Z | utils/data_utils.py | google/gcnn-survey-paper | 591af8d6c4374378831cab2cdec79575e2540d79 | [
"Apache-2.0"
] | null | null | null | utils/data_utils.py | google/gcnn-survey-paper | 591af8d6c4374378831cab2cdec79575e2540d79 | [
"Apache-2.0"
] | 23 | 2020-05-11T12:39:58.000Z | 2022-03-04T09:13:58.000Z | #Copyright 2018 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.
"""Utils functions to load and process citation data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import pickle as pkl
import sys
import networkx as nx
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import tensorflow as tf
from third_party.gcn.gcn.utils import normalize_adj
from third_party.gcn.gcn.utils import parse_index_file
from third_party.gcn.gcn.utils import sample_mask
from third_party.gcn.gcn.utils import sparse_to_tuple
from third_party.gcn.gcn.utils import preprocess_features
def load_test_edge_mask(dataset_str, data_path, drop_edge_prop):
"""Remove test edges by loading edge masks."""
edge_mask_path = os.path.join(
data_path, 'emask.{}.remove{}.npz'.format(dataset_str, drop_edge_prop))
with tf.gfile.Open(edge_mask_path) as f:
mask = sp.load_npz(f)
return mask
def load_edge_masks(dataset_str, data_path, adj_true, drop_edge_prop):
"""Loads adjacency matrix as sparse matrix and masks for val & test links.
Args:
dataset_str: dataset to use
data_path: path to data folder
adj_true: true adjacency matrix in dense format,
drop_edge_prop: proportion of edges to remove.
Returns:
adj_matrix: adjacency matrix
train_mask: mask for train edges
val_mask: mask for val edges
test_mask: mask for test edges
"""
edge_mask_path = os.path.join(
data_path, 'emask.{}.remove{}.'.format(dataset_str, drop_edge_prop))
val_mask = sp.load_npz(edge_mask_path + 'val.npz')
test_mask = sp.load_npz(edge_mask_path + 'test.npz')
train_mask = 1. - val_mask.todense() - test_mask.todense()
# remove val and test edges from true A
adj_train = np.multiply(adj_true, train_mask)
train_mask -= np.eye(train_mask.shape[0])
return adj_train, sparse_to_tuple(val_mask), sparse_to_tuple(
val_mask), sparse_to_tuple(test_mask)
def add_top_k_edges(data, edge_mask_path, gae_scores_path, topk, nb_nodes,
norm_adj):
"""Loads GAE scores and adds topK edges to train adjacency."""
test_mask = sp.load_npz(os.path.join(edge_mask_path, 'test_mask.npz'))
train_mask = 1. - test_mask.todense()
# remove val and test edges from true A
adj_train_curr = np.multiply(data['adj_true'], train_mask)
# Predict test edges using precomputed scores
scores = np.load(os.path.join(gae_scores_path, 'gae_scores.npy'))
# scores_mask = 1 - np.eye(nb_nodes)
scores_mask = np.zeros((nb_nodes, nb_nodes))
scores_mask[:140, 140:] = 1.
scores_mask[140:, :140] = 1.
scores = np.multiply(scores, scores_mask).reshape((-1,))
threshold = scores[np.argsort(-scores)[topk]]
adj_train_curr += 1 * (scores > threshold).reshape((nb_nodes, nb_nodes))
adj_train_curr = 1 * (adj_train_curr > 0)
if norm_adj:
adj_train_norm = normalize_adj(data['adj_train'])
else:
adj_train_norm = sp.coo_matrix(data['adj_train'])
return adj_train_curr, sparse_to_tuple(adj_train_norm)
def process_adj(adj, model_name):
"""Symmetrically normalize adjacency matrix."""
if model_name == 'Cheby':
laplacian = sp.eye(adj.shape[0]) - normalize_adj(adj - sp.eye(adj.shape[0]))
# TODO(chamii): compare with
# adj)
largest_eigval, _ = eigsh(laplacian, 1, which='LM')
laplacian_norm = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])
return laplacian_norm
else:
return normalize_adj(adj)
def load_data(dataset_str, data_path):
if dataset_str in ['cora', 'citeseer', 'pubmed']:
return load_citation_data(dataset_str, data_path)
else:
return load_ppi_data(data_path)
def load_ppi_data(data_path):
"""Load PPI dataset."""
with tf.gfile.Open(os.path.join(data_path, 'ppi.edges.npz')) as f:
adj = sp.load_npz(f)
with tf.gfile.Open(os.path.join(data_path, 'ppi.features.norm.npy')) as f:
features = np.load(f)
with tf.gfile.Open(os.path.join(data_path, 'ppi.labels.npz')) as f:
labels = sp.load_npz(f).todense()
train_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.train_mask.npy'))) > 0
val_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.test_mask.npy'))) > 0
test_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.test_mask.npy'))) > 0
return adj, features, labels, train_mask, val_mask, test_mask
def load_citation_data(dataset_str, data_path):
"""Load data."""
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = {}
for name in names:
with tf.gfile.Open(
os.path.join(data_path, 'ind.{}.{}'.format(dataset_str, name)),
'rb') as f:
if sys.version_info > (3, 0):
objects[name] = pkl.load(f) # , encoding='latin1') comment to pass lint
else:
objects[name] = pkl.load(f)
test_idx_reorder = parse_index_file(
os.path.join(data_path, 'ind.{}.test.index'.format(dataset_str)))
test_idx_range = np.sort(test_idx_reorder)
if dataset_str == 'citeseer':
# Fix citeseer dataset (there are some isolated nodes in the graph)
# Find isolated nodes, add them as zero-vecs into the right position
test_idx_range_full = range(
min(test_idx_reorder),
max(test_idx_reorder) + 1)
tx_extended = sp.lil_matrix((len(test_idx_range_full),
objects['x'].shape[1]))
tx_extended[test_idx_range - min(test_idx_range), :] = objects['tx']
objects['tx'] = tx_extended
ty_extended = np.zeros((len(test_idx_range_full),
objects['y'].shape[1]))
ty_extended[test_idx_range - min(test_idx_range), :] = objects['ty']
objects['ty'] = ty_extended
features = sp.vstack((objects['allx'], objects['tx'])).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
adj = nx.adjacency_matrix(nx.from_dict_of_lists(objects['graph']))
labels = np.vstack((objects['ally'], objects['ty']))
labels[test_idx_reorder, :] = labels[test_idx_range, :]
idx_test = test_idx_range.tolist()
idx_train = range(len(objects['y']))
idx_val = range(len(objects['y']), len(objects['y']) + 500)
train_mask = sample_mask(idx_train, labels.shape[0])
val_mask = sample_mask(idx_val, labels.shape[0])
test_mask = sample_mask(idx_test, labels.shape[0])
features = preprocess_features(features)
return adj, features, labels, train_mask, val_mask, test_mask
def construct_feed_dict(adj_normalized, adj, features, placeholders):
# construct feed dictionary
feed_dict = dict()
feed_dict.update({placeholders['features']: features})
feed_dict.update({placeholders['adj']: adj_normalized})
feed_dict.update({placeholders['adj_orig']: adj})
return feed_dict
def mask_val_test_edges(adj, prop):
"""Function to mask test and val edges."""
# NOTE: Splits are randomized and results might slightly
# deviate from reported numbers in the paper.
# Remove diagonal elements
adj = adj - sp.dia_matrix(
(adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)
adj.eliminate_zeros()
# Check that diag is zero:
assert np.diag(adj.todense()).sum() == 0
adj_triu = sp.triu(adj)
adj_tuple = sparse_to_tuple(adj_triu)
edges = adj_tuple[0]
edges_all = sparse_to_tuple(adj)[0]
num_test = int(np.floor(edges.shape[0] * prop))
# num_val = int(np.floor(edges.shape[0] * 0.05)) # we keep 5% for validation
# we keep 10% of training edges for validation
num_val = int(np.floor((edges.shape[0] - num_test) * 0.05))
all_edge_idx = range(edges.shape[0])
np.random.shuffle(all_edge_idx)
val_edge_idx = all_edge_idx[:num_val]
test_edge_idx = all_edge_idx[num_val:(num_val + num_test)]
test_edges = edges[test_edge_idx]
val_edges = edges[val_edge_idx]
train_edges = np.delete(
edges, np.hstack([test_edge_idx, val_edge_idx]), axis=0)
def ismember(a, b, tol=5):
rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)
return np.any(rows_close)
test_edges_false = []
while len(test_edges_false) < len(test_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], edges_all):
continue
if test_edges_false:
if ismember([idx_j, idx_i], np.array(test_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(test_edges_false)):
continue
test_edges_false.append([idx_i, idx_j])
val_edges_false = []
while len(val_edges_false) < len(val_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], train_edges):
continue
if ismember([idx_j, idx_i], train_edges):
continue
if ismember([idx_i, idx_j], val_edges):
continue
if ismember([idx_j, idx_i], val_edges):
continue
if val_edges_false:
if ismember([idx_j, idx_i], np.array(val_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(val_edges_false)):
continue
val_edges_false.append([idx_i, idx_j])
assert ~ismember(test_edges_false, edges_all)
assert ~ismember(val_edges_false, edges_all)
assert ~ismember(val_edges, train_edges)
assert ~ismember(test_edges, train_edges)
assert ~ismember(val_edges, test_edges)
data = np.ones(train_edges.shape[0])
# Re-build adj matrix
adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])),
shape=adj.shape)
adj_train = adj_train + adj_train.T
# NOTE: these edge lists only contain single direction of edge!
num_nodes = adj.shape[0]
val_mask = np.zeros((num_nodes, num_nodes))
for i, j in val_edges:
val_mask[i, j] = 1
val_mask[j, i] = 1
for i, j in val_edges_false:
val_mask[i, j] = 1
val_mask[j, i] = 1
test_mask = np.zeros((num_nodes, num_nodes))
for i, j in test_edges:
test_mask[i, j] = 1
test_mask[j, i] = 1
for i, j in test_edges_false:
test_mask[i, j] = 1
test_mask[j, i] = 1
return adj_train, sparse_to_tuple(val_mask), sparse_to_tuple(test_mask)
def mask_test_edges(adj, prop):
"""Function to mask test edges.
Args:
adj: scipy sparse matrix
prop: proportion of edges to remove (float in [0, 1])
Returns:
adj_train: adjacency with edges removed
test_edges: list of positive and negative test edges
"""
# Remove diagonal elements
adj = adj - sp.dia_matrix(
(adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)
adj.eliminate_zeros()
# Check that diag is zero:
assert np.diag(adj.todense()).sum() == 0
adj_triu = sp.triu(adj)
adj_tuple = sparse_to_tuple(adj_triu)
edges = adj_tuple[0]
edges_all = sparse_to_tuple(adj)[0]
num_test = int(np.floor(edges.shape[0] * prop))
all_edge_idx = range(edges.shape[0])
np.random.shuffle(all_edge_idx)
test_edge_idx = all_edge_idx[:num_test]
test_edges = edges[test_edge_idx]
train_edges = np.delete(edges, test_edge_idx, axis=0)
def ismember(a, b, tol=5):
rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)
return np.any(rows_close)
test_edges_false = []
while len(test_edges_false) < len(test_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], edges_all):
continue
if test_edges_false:
if ismember([idx_j, idx_i], np.array(test_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(test_edges_false)):
continue
test_edges_false.append([idx_i, idx_j])
assert ~ismember(test_edges_false, edges_all)
assert ~ismember(test_edges, train_edges)
data = np.ones(train_edges.shape[0])
# Re-build adj matrix
adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])),
shape=adj.shape)
adj_train = adj_train + adj_train.T
# NOTE: these edge lists only contain single direction of edge!
num_nodes = adj.shape[0]
test_mask = np.zeros((num_nodes, num_nodes))
for i, j in test_edges:
test_mask[i, j] = 1
test_mask[j, i] = 1
for i, j in test_edges_false:
test_mask[i, j] = 1
test_mask[j, i] = 1
return adj_train, sparse_to_tuple(test_mask)
| 34.772358 | 80 | 0.691996 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import pickle as pkl
import sys
import networkx as nx
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import tensorflow as tf
from third_party.gcn.gcn.utils import normalize_adj
from third_party.gcn.gcn.utils import parse_index_file
from third_party.gcn.gcn.utils import sample_mask
from third_party.gcn.gcn.utils import sparse_to_tuple
from third_party.gcn.gcn.utils import preprocess_features
def load_test_edge_mask(dataset_str, data_path, drop_edge_prop):
edge_mask_path = os.path.join(
data_path, 'emask.{}.remove{}.npz'.format(dataset_str, drop_edge_prop))
with tf.gfile.Open(edge_mask_path) as f:
mask = sp.load_npz(f)
return mask
def load_edge_masks(dataset_str, data_path, adj_true, drop_edge_prop):
edge_mask_path = os.path.join(
data_path, 'emask.{}.remove{}.'.format(dataset_str, drop_edge_prop))
val_mask = sp.load_npz(edge_mask_path + 'val.npz')
test_mask = sp.load_npz(edge_mask_path + 'test.npz')
train_mask = 1. - val_mask.todense() - test_mask.todense()
adj_train = np.multiply(adj_true, train_mask)
train_mask -= np.eye(train_mask.shape[0])
return adj_train, sparse_to_tuple(val_mask), sparse_to_tuple(
val_mask), sparse_to_tuple(test_mask)
def add_top_k_edges(data, edge_mask_path, gae_scores_path, topk, nb_nodes,
norm_adj):
test_mask = sp.load_npz(os.path.join(edge_mask_path, 'test_mask.npz'))
train_mask = 1. - test_mask.todense()
adj_train_curr = np.multiply(data['adj_true'], train_mask)
scores = np.load(os.path.join(gae_scores_path, 'gae_scores.npy'))
scores_mask = np.zeros((nb_nodes, nb_nodes))
scores_mask[:140, 140:] = 1.
scores_mask[140:, :140] = 1.
scores = np.multiply(scores, scores_mask).reshape((-1,))
threshold = scores[np.argsort(-scores)[topk]]
adj_train_curr += 1 * (scores > threshold).reshape((nb_nodes, nb_nodes))
adj_train_curr = 1 * (adj_train_curr > 0)
if norm_adj:
adj_train_norm = normalize_adj(data['adj_train'])
else:
adj_train_norm = sp.coo_matrix(data['adj_train'])
return adj_train_curr, sparse_to_tuple(adj_train_norm)
def process_adj(adj, model_name):
if model_name == 'Cheby':
laplacian = sp.eye(adj.shape[0]) - normalize_adj(adj - sp.eye(adj.shape[0]))
largest_eigval, _ = eigsh(laplacian, 1, which='LM')
laplacian_norm = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])
return laplacian_norm
else:
return normalize_adj(adj)
def load_data(dataset_str, data_path):
if dataset_str in ['cora', 'citeseer', 'pubmed']:
return load_citation_data(dataset_str, data_path)
else:
return load_ppi_data(data_path)
def load_ppi_data(data_path):
with tf.gfile.Open(os.path.join(data_path, 'ppi.edges.npz')) as f:
adj = sp.load_npz(f)
with tf.gfile.Open(os.path.join(data_path, 'ppi.features.norm.npy')) as f:
features = np.load(f)
with tf.gfile.Open(os.path.join(data_path, 'ppi.labels.npz')) as f:
labels = sp.load_npz(f).todense()
train_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.train_mask.npy'))) > 0
val_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.test_mask.npy'))) > 0
test_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.test_mask.npy'))) > 0
return adj, features, labels, train_mask, val_mask, test_mask
def load_citation_data(dataset_str, data_path):
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = {}
for name in names:
with tf.gfile.Open(
os.path.join(data_path, 'ind.{}.{}'.format(dataset_str, name)),
'rb') as f:
if sys.version_info > (3, 0):
objects[name] = pkl.load(f)
else:
objects[name] = pkl.load(f)
test_idx_reorder = parse_index_file(
os.path.join(data_path, 'ind.{}.test.index'.format(dataset_str)))
test_idx_range = np.sort(test_idx_reorder)
if dataset_str == 'citeseer':
test_idx_range_full = range(
min(test_idx_reorder),
max(test_idx_reorder) + 1)
tx_extended = sp.lil_matrix((len(test_idx_range_full),
objects['x'].shape[1]))
tx_extended[test_idx_range - min(test_idx_range), :] = objects['tx']
objects['tx'] = tx_extended
ty_extended = np.zeros((len(test_idx_range_full),
objects['y'].shape[1]))
ty_extended[test_idx_range - min(test_idx_range), :] = objects['ty']
objects['ty'] = ty_extended
features = sp.vstack((objects['allx'], objects['tx'])).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
adj = nx.adjacency_matrix(nx.from_dict_of_lists(objects['graph']))
labels = np.vstack((objects['ally'], objects['ty']))
labels[test_idx_reorder, :] = labels[test_idx_range, :]
idx_test = test_idx_range.tolist()
idx_train = range(len(objects['y']))
idx_val = range(len(objects['y']), len(objects['y']) + 500)
train_mask = sample_mask(idx_train, labels.shape[0])
val_mask = sample_mask(idx_val, labels.shape[0])
test_mask = sample_mask(idx_test, labels.shape[0])
features = preprocess_features(features)
return adj, features, labels, train_mask, val_mask, test_mask
def construct_feed_dict(adj_normalized, adj, features, placeholders):
feed_dict = dict()
feed_dict.update({placeholders['features']: features})
feed_dict.update({placeholders['adj']: adj_normalized})
feed_dict.update({placeholders['adj_orig']: adj})
return feed_dict
def mask_val_test_edges(adj, prop):
adj = adj - sp.dia_matrix(
(adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)
adj.eliminate_zeros()
assert np.diag(adj.todense()).sum() == 0
adj_triu = sp.triu(adj)
adj_tuple = sparse_to_tuple(adj_triu)
edges = adj_tuple[0]
edges_all = sparse_to_tuple(adj)[0]
num_test = int(np.floor(edges.shape[0] * prop))
r((edges.shape[0] - num_test) * 0.05))
all_edge_idx = range(edges.shape[0])
np.random.shuffle(all_edge_idx)
val_edge_idx = all_edge_idx[:num_val]
test_edge_idx = all_edge_idx[num_val:(num_val + num_test)]
test_edges = edges[test_edge_idx]
val_edges = edges[val_edge_idx]
train_edges = np.delete(
edges, np.hstack([test_edge_idx, val_edge_idx]), axis=0)
def ismember(a, b, tol=5):
rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)
return np.any(rows_close)
test_edges_false = []
while len(test_edges_false) < len(test_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], edges_all):
continue
if test_edges_false:
if ismember([idx_j, idx_i], np.array(test_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(test_edges_false)):
continue
test_edges_false.append([idx_i, idx_j])
val_edges_false = []
while len(val_edges_false) < len(val_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], train_edges):
continue
if ismember([idx_j, idx_i], train_edges):
continue
if ismember([idx_i, idx_j], val_edges):
continue
if ismember([idx_j, idx_i], val_edges):
continue
if val_edges_false:
if ismember([idx_j, idx_i], np.array(val_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(val_edges_false)):
continue
val_edges_false.append([idx_i, idx_j])
assert ~ismember(test_edges_false, edges_all)
assert ~ismember(val_edges_false, edges_all)
assert ~ismember(val_edges, train_edges)
assert ~ismember(test_edges, train_edges)
assert ~ismember(val_edges, test_edges)
data = np.ones(train_edges.shape[0])
adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])),
shape=adj.shape)
adj_train = adj_train + adj_train.T
num_nodes = adj.shape[0]
val_mask = np.zeros((num_nodes, num_nodes))
for i, j in val_edges:
val_mask[i, j] = 1
val_mask[j, i] = 1
for i, j in val_edges_false:
val_mask[i, j] = 1
val_mask[j, i] = 1
test_mask = np.zeros((num_nodes, num_nodes))
for i, j in test_edges:
test_mask[i, j] = 1
test_mask[j, i] = 1
for i, j in test_edges_false:
test_mask[i, j] = 1
test_mask[j, i] = 1
return adj_train, sparse_to_tuple(val_mask), sparse_to_tuple(test_mask)
def mask_test_edges(adj, prop):
adj = adj - sp.dia_matrix(
(adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)
adj.eliminate_zeros()
assert np.diag(adj.todense()).sum() == 0
adj_triu = sp.triu(adj)
adj_tuple = sparse_to_tuple(adj_triu)
edges = adj_tuple[0]
edges_all = sparse_to_tuple(adj)[0]
num_test = int(np.floor(edges.shape[0] * prop))
all_edge_idx = range(edges.shape[0])
np.random.shuffle(all_edge_idx)
test_edge_idx = all_edge_idx[:num_test]
test_edges = edges[test_edge_idx]
train_edges = np.delete(edges, test_edge_idx, axis=0)
def ismember(a, b, tol=5):
rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)
return np.any(rows_close)
test_edges_false = []
while len(test_edges_false) < len(test_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], edges_all):
continue
if test_edges_false:
if ismember([idx_j, idx_i], np.array(test_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(test_edges_false)):
continue
test_edges_false.append([idx_i, idx_j])
assert ~ismember(test_edges_false, edges_all)
assert ~ismember(test_edges, train_edges)
data = np.ones(train_edges.shape[0])
adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])),
shape=adj.shape)
adj_train = adj_train + adj_train.T
num_nodes = adj.shape[0]
test_mask = np.zeros((num_nodes, num_nodes))
for i, j in test_edges:
test_mask[i, j] = 1
test_mask[j, i] = 1
for i, j in test_edges_false:
test_mask[i, j] = 1
test_mask[j, i] = 1
return adj_train, sparse_to_tuple(test_mask)
| true | true |
f72c2b187dd8c532b6839213766774021ef6ff74 | 33 | py | Python | tests/__init__.py | yoophi/flask-google-login-example | 57cbbcbd054a6ba47c2a492950bf500b6b595b7d | [
"MIT"
] | null | null | null | tests/__init__.py | yoophi/flask-google-login-example | 57cbbcbd054a6ba47c2a492950bf500b6b595b7d | [
"MIT"
] | null | null | null | tests/__init__.py | yoophi/flask-google-login-example | 57cbbcbd054a6ba47c2a492950bf500b6b595b7d | [
"MIT"
] | null | null | null | """Unit test package for app."""
| 16.5 | 32 | 0.636364 | true | true | |
f72c2cf7b738c597ce705f662cdf1e0bb2603530 | 323 | py | Python | mmcap/models/utils/__init__.py | hnp0411/mmcaptioning | 47bcdee3734cdaaa96a34e927cdec5cc43cab538 | [
"Apache-2.0"
] | null | null | null | mmcap/models/utils/__init__.py | hnp0411/mmcaptioning | 47bcdee3734cdaaa96a34e927cdec5cc43cab538 | [
"Apache-2.0"
] | null | null | null | mmcap/models/utils/__init__.py | hnp0411/mmcaptioning | 47bcdee3734cdaaa96a34e927cdec5cc43cab538 | [
"Apache-2.0"
] | null | null | null | from .gaussian_target import gaussian_radius, gen_gaussian_target
from .res_layer import ResLayer
from .position_embedding_2d import PositionEmbeddingSine
from .sampling import topktopp
__all__ = ['ResLayer',
'gaussian_radius', 'gen_gaussian_target',
'PositionEmbeddingSine',
'topktopp']
| 32.3 | 65 | 0.749226 | from .gaussian_target import gaussian_radius, gen_gaussian_target
from .res_layer import ResLayer
from .position_embedding_2d import PositionEmbeddingSine
from .sampling import topktopp
__all__ = ['ResLayer',
'gaussian_radius', 'gen_gaussian_target',
'PositionEmbeddingSine',
'topktopp']
| true | true |
f72c2daa1aa4397686149633191ba4e69a6e8ed2 | 425 | py | Python | MachineLearning/DecisionTree/loan_delinquency.py | yexianyi/AI_Practice | 80499ab3a06ac055641aa069fe1e37864c9e41c4 | [
"Apache-2.0"
] | null | null | null | MachineLearning/DecisionTree/loan_delinquency.py | yexianyi/AI_Practice | 80499ab3a06ac055641aa069fe1e37864c9e41c4 | [
"Apache-2.0"
] | null | null | null | MachineLearning/DecisionTree/loan_delinquency.py | yexianyi/AI_Practice | 80499ab3a06ac055641aa069fe1e37864c9e41c4 | [
"Apache-2.0"
] | null | null | null | '''
Decision Tree
Predict if it is possible to default on the loan
'''
import numpy as np
from sklearn import tree
data = np.genfromtxt("exercise.csv", delimiter=",")
# get train data set
x_data = data[1:, 1:-1]
# get test data set
y_data = data[1:, -1]
print(x_data)
print(y_data)
# Create decision tree
dtree = tree.DecisionTreeClassifier(min_samples_leaf=5)
dtree.fit(x_data, y_data)
print(dtree.score(x_data, y_data))
| 20.238095 | 55 | 0.734118 | import numpy as np
from sklearn import tree
data = np.genfromtxt("exercise.csv", delimiter=",")
x_data = data[1:, 1:-1]
y_data = data[1:, -1]
print(x_data)
print(y_data)
dtree = tree.DecisionTreeClassifier(min_samples_leaf=5)
dtree.fit(x_data, y_data)
print(dtree.score(x_data, y_data))
| true | true |
f72c2df55f1cc8270d405748ec5245b4671cc4a9 | 1,680 | py | Python | test/test_flac3d.py | ffilotto/meshio | 4413be41e6a63e33273665986f42dab80d585d10 | [
"MIT"
] | null | null | null | test/test_flac3d.py | ffilotto/meshio | 4413be41e6a63e33273665986f42dab80d585d10 | [
"MIT"
] | null | null | null | test/test_flac3d.py | ffilotto/meshio | 4413be41e6a63e33273665986f42dab80d585d10 | [
"MIT"
] | null | null | null | import copy
import pathlib
import sys
import helpers
import numpy
import pytest
import meshio
@pytest.mark.parametrize(
"mesh, binary, data",
[
(helpers.tet_mesh, False, []),
(helpers.hex_mesh, False, []),
(helpers.tet_mesh, False, [1, 2]),
(helpers.tet_mesh, True, []),
(helpers.hex_mesh, True, []),
(helpers.tet_mesh, True, [1, 2]),
],
)
def test(mesh, binary, data):
if data:
mesh = copy.deepcopy(mesh)
mesh.cell_data["flac3d:zone"] = [numpy.array(data)]
helpers.write_read(
lambda f, m: meshio.flac3d.write(f, m, binary=binary),
meshio.flac3d.read,
mesh,
1.0e-15,
)
# the failure perhaps has to do with dictionary ordering
@pytest.mark.skipif(sys.version_info < (3, 6), reason="Fails with 3.5")
@pytest.mark.parametrize(
"filename", ["flac3d_mesh_ex.f3grid", "flac3d_mesh_ex_bin.f3grid"],
)
def test_reference_file(filename):
this_dir = pathlib.Path(__file__).resolve().parent
filename = this_dir / "meshes" / "flac3d" / filename
mesh = meshio.read(filename)
# points
assert numpy.isclose(mesh.points.sum(), 307.0)
# cells
ref_num_cells = [
("hexahedron", 45),
("pyramid", 9),
("hexahedron", 18),
("wedge", 9),
("hexahedron", 6),
("wedge", 3),
("hexahedron", 6),
("wedge", 3),
("pyramid", 6),
("tetra", 3),
]
assert [(k, len(v)) for k, v in mesh.cells] == ref_num_cells
# Cell data
ref_sum_cell_data = [45, 9, 18, 9, 6, 3, 6, 3, 6, 3]
assert [len(arr) for arr in mesh.cell_data["flac3d:zone"]] == ref_sum_cell_data
| 25.454545 | 83 | 0.583333 | import copy
import pathlib
import sys
import helpers
import numpy
import pytest
import meshio
@pytest.mark.parametrize(
"mesh, binary, data",
[
(helpers.tet_mesh, False, []),
(helpers.hex_mesh, False, []),
(helpers.tet_mesh, False, [1, 2]),
(helpers.tet_mesh, True, []),
(helpers.hex_mesh, True, []),
(helpers.tet_mesh, True, [1, 2]),
],
)
def test(mesh, binary, data):
if data:
mesh = copy.deepcopy(mesh)
mesh.cell_data["flac3d:zone"] = [numpy.array(data)]
helpers.write_read(
lambda f, m: meshio.flac3d.write(f, m, binary=binary),
meshio.flac3d.read,
mesh,
1.0e-15,
)
@pytest.mark.skipif(sys.version_info < (3, 6), reason="Fails with 3.5")
@pytest.mark.parametrize(
"filename", ["flac3d_mesh_ex.f3grid", "flac3d_mesh_ex_bin.f3grid"],
)
def test_reference_file(filename):
this_dir = pathlib.Path(__file__).resolve().parent
filename = this_dir / "meshes" / "flac3d" / filename
mesh = meshio.read(filename)
assert numpy.isclose(mesh.points.sum(), 307.0)
ref_num_cells = [
("hexahedron", 45),
("pyramid", 9),
("hexahedron", 18),
("wedge", 9),
("hexahedron", 6),
("wedge", 3),
("hexahedron", 6),
("wedge", 3),
("pyramid", 6),
("tetra", 3),
]
assert [(k, len(v)) for k, v in mesh.cells] == ref_num_cells
ref_sum_cell_data = [45, 9, 18, 9, 6, 3, 6, 3, 6, 3]
assert [len(arr) for arr in mesh.cell_data["flac3d:zone"]] == ref_sum_cell_data
| true | true |
f72c2f6aa5e33817498aeaf30c0f710fd5347dc0 | 471 | py | Python | examples/idioms/programs/177.3241-find-files-with-a-given-list-of-filename-extensions.py | laowantong/paroxython | 4626798a60eeaa765dbfab9e63e04030c9fcb1d0 | [
"MIT"
] | 31 | 2020-05-02T13:34:26.000Z | 2021-06-06T17:25:52.000Z | examples/idioms/programs/177.3241-find-files-with-a-given-list-of-filename-extensions.py | laowantong/paroxython | 4626798a60eeaa765dbfab9e63e04030c9fcb1d0 | [
"MIT"
] | 108 | 2019-11-18T19:41:52.000Z | 2022-03-18T13:58:17.000Z | examples/idioms/programs/177.3241-find-files-with-a-given-list-of-filename-extensions.py | laowantong/paroxython | 4626798a60eeaa765dbfab9e63e04030c9fcb1d0 | [
"MIT"
] | 4 | 2020-05-19T08:57:44.000Z | 2020-09-21T08:53:46.000Z | """Find files with a given list of filename extensions.
Construct a list _L that contains all filenames that have the extension ".jpg" , ".jpeg" or ".png" in directory _D and all it's subdirectories.
Source: Bart
"""
# Implementation author: charlax
# Created on 2019-09-27T11:33:27.420533Z
# Last modified on 2019-09-27T11:33:27.420533Z
# Version 1
import glob
import itertools
list(itertools.chain(*(glob.glob("*/**.%s" % ext) for ext in ["jpg", "jpeg", "png"])))
| 27.705882 | 143 | 0.713376 |
import glob
import itertools
list(itertools.chain(*(glob.glob("*/**.%s" % ext) for ext in ["jpg", "jpeg", "png"])))
| true | true |
f72c31469cfb67208d5848f60740b7c718ec496d | 160 | py | Python | src/battery/battery.py | BigOz/flourish | a45f9d0290878c69237fdd1949ee42f9e6039df9 | [
"BSD-2-Clause"
] | null | null | null | src/battery/battery.py | BigOz/flourish | a45f9d0290878c69237fdd1949ee42f9e6039df9 | [
"BSD-2-Clause"
] | null | null | null | src/battery/battery.py | BigOz/flourish | a45f9d0290878c69237fdd1949ee42f9e6039df9 | [
"BSD-2-Clause"
] | null | null | null | class Battery:
def __init__(self, evaluator):
raise NotImplementedError
def get_action(self, current_state):
raise NotImplementedError
| 22.857143 | 40 | 0.7125 | class Battery:
def __init__(self, evaluator):
raise NotImplementedError
def get_action(self, current_state):
raise NotImplementedError
| true | true |
f72c3198aa025287611b7e30ff0d1259ec7834b8 | 8,969 | py | Python | cache_dependencies/tests/test_transaction.py | Tusky/cache-dependencies | 6c19d0c2adfce19c3fdc53ad5704eddc6d84e106 | [
"BSD-3-Clause"
] | 3 | 2017-08-08T20:06:56.000Z | 2018-09-19T03:16:20.000Z | cache_dependencies/tests/test_transaction.py | Tusky/cache-dependencies | 6c19d0c2adfce19c3fdc53ad5704eddc6d84e106 | [
"BSD-3-Clause"
] | 1 | 2017-10-24T23:11:32.000Z | 2017-10-24T23:11:32.000Z | cache_dependencies/tests/test_transaction.py | Tusky/cache-dependencies | 6c19d0c2adfce19c3fdc53ad5704eddc6d84e106 | [
"BSD-3-Clause"
] | 8 | 2017-10-24T07:43:56.000Z | 2021-06-17T07:03:02.000Z | import time
import unittest
from cache_dependencies import interfaces, transaction
try:
from unittest import mock
except ImportError:
import mock
try:
str = unicode # Python 2.* compatible
string_types = (basestring,)
integer_types = (int, long)
except NameError:
string_types = (str,)
integer_types = (int,)
class AbstractTransactionTestCase(unittest.TestCase):
def setUp(self):
self.current_time = mock.Mock(return_value=time.time())
self.lock = mock.Mock(spec=interfaces.IDependency)
self.parent = mock.Mock(spec=interfaces.ITransaction)
self.transaction = self._make_transaction(self.lock, self.parent, self.current_time)
self.dependency = self._make_dependency()
def _make_transaction(self, lock, parent, current_time_accessor):
raise NotImplementedError
@staticmethod
def _make_dependency():
instance = mock.Mock(spec=interfaces.IDependency)
instance.extend = mock.Mock(return_value=True)
return instance
def test_evaluate(self):
self.transaction.evaluate(self.dependency, 1)
self.lock.evaluate.assert_called_once_with(self.dependency, self.transaction, 1)
def test_get_session_id(self):
session1_id = self.transaction.get_session_id()
session2_id = self.transaction.get_session_id()
self.assertEqual(session1_id, session2_id)
self.assertIsInstance(session2_id, string_types)
def run(self, result=None):
if self.__class__.__name__.startswith('Abstract'):
return
super(AbstractTransactionTestCase, self).run(result)
class TransactionTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
class Transaction(transaction.Transaction):
_current_time = current_time_accessor
return Transaction(lock)
def test_parent(self):
self.assertIsNone(self.transaction.parent())
def test_get_start_time(self):
self.current_time.reset_mock()
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_start_time(), initial_return_value)
self.current_time.assert_not_called()
def test_get_end_time(self):
self.current_time.reset_mock()
with self.assertRaises(RuntimeError):
self.transaction.get_end_time()
self.current_time.return_value += 1
self.transaction.finish()
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_end_time(), initial_return_value)
self.current_time.assert_called_once_with()
def test_add_dependency_and_finish(self):
dependency1 = self._make_dependency()
dependency1.id = 1
dependency2 = self._make_dependency()
dependency2.id = 2
dependency3 = self._make_dependency()
dependency3.id = 3
self.transaction.add_dependency(dependency1, None)
self.lock.acquire.assert_called_once_with(dependency1, self.transaction, None)
self.lock.reset_mock()
self.transaction.add_dependency(dependency2, None)
self.lock.acquire.assert_called_once_with(dependency2, self.transaction, None)
self.lock.reset_mock()
dependency1.extend.assert_called_once_with(dependency2)
dependency1.reset_mock()
self.transaction.add_dependency(dependency3, 1)
self.lock.acquire.assert_called_once_with(dependency3, self.transaction, 1)
self.lock.reset_mock()
dependency1.extend.assert_not_called()
self.transaction.finish()
self.assertEqual(self.lock.release.call_count, 2)
args, kwargs = self.lock.release.call_args_list[-1]
self.assertEqual(len(args[0].delegates), 1)
self.assertEqual(args[0].delegates[0].id, 1)
self.assertIs(args[1], self.transaction)
self.assertIsNone(args[2])
args, kwargs = self.lock.release.call_args_list[-2]
self.assertEqual(len(args[0].delegates), 1)
self.assertEqual(args[0].delegates[0].id, 3)
self.assertIs(args[1], self.transaction)
self.assertEqual(args[2], 1)
def test_bool(self):
self.assertTrue(self.transaction)
class SavePointTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
return transaction.SavePoint(lock, parent)
def test_parent(self):
self.assertIs(self.transaction.parent(), self.parent)
def test_get_start_time(self):
self.transaction.get_start_time()
self.parent.get_start_time.assert_called_once_with()
def test_get_end_time(self):
self.transaction.get_end_time()
self.parent.get_end_time.assert_called_once_with()
def test_add_dependency(self):
self.transaction.add_dependency(self.dependency, 1)
self.lock.acquire.assert_called_once_with(self.dependency, self.transaction, 1)
self.parent.add_dependency.assert_called_once_with(self.dependency, 1)
def test_bool(self):
self.assertTrue(self.transaction)
class DummyTransactionTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
class DummyTransaction(transaction.DummyTransaction):
_current_time = current_time_accessor
return DummyTransaction(lock)
def test_parent(self):
self.assertIsNone(self.transaction.parent())
def test_get_start_time(self):
self.current_time.reset_mock()
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
self.assertEqual(self.current_time.call_count, 2)
def test_get_end_time(self):
self.current_time.reset_mock()
self.current_time.return_value += 1
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
self.assertEqual(self.current_time.call_count, 2)
def test_bool(self):
self.assertFalse(self.transaction)
class TransactionManagerTestCase(unittest.TestCase):
def setUp(self):
self.transaction = mock.Mock(spec=interfaces.ITransaction)
self.lock = mock.Mock(spec=interfaces.IDependency)
self.transaction_manager = transaction.TransactionManager(self.lock)
def test_current_none(self):
current_transaction = self.transaction_manager.current()
self.assertIsInstance(current_transaction, transaction.DummyTransaction)
def test_current_set_get(self):
self.transaction_manager.current(self.transaction)
self.assertIs(self.transaction_manager.current(), self.transaction)
def test_begin(self):
initial_transaction = self.transaction_manager.begin()
self.assertIsInstance(initial_transaction, transaction.Transaction)
save_point = self.transaction_manager.begin()
self.assertIsInstance(save_point, transaction.SavePoint)
self.assertIs(save_point.parent(), initial_transaction)
nested_save_point = self.transaction_manager.begin()
self.assertIsInstance(nested_save_point, transaction.SavePoint)
self.assertIs(nested_save_point.parent(), save_point)
def test_finish_delegate_transaction(self):
self.transaction_manager.current(self.transaction)
self.transaction_manager.finish()
self.transaction.finish.assert_called_once_with()
def test_finish_transaction(self):
self.transaction_manager.begin()
self.transaction_manager.finish()
self.assertIsInstance(self.transaction_manager.current(), transaction.DummyTransaction)
def test_finish_savepoint(self):
initial_transaction = self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.finish()
self.assertIs(self.transaction_manager.current(), initial_transaction)
def test_flush(self):
self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.flush()
self.assertIsInstance(self.transaction_manager.current(), transaction.DummyTransaction)
| 38.659483 | 97 | 0.721485 | import time
import unittest
from cache_dependencies import interfaces, transaction
try:
from unittest import mock
except ImportError:
import mock
try:
str = unicode
string_types = (basestring,)
integer_types = (int, long)
except NameError:
string_types = (str,)
integer_types = (int,)
class AbstractTransactionTestCase(unittest.TestCase):
def setUp(self):
self.current_time = mock.Mock(return_value=time.time())
self.lock = mock.Mock(spec=interfaces.IDependency)
self.parent = mock.Mock(spec=interfaces.ITransaction)
self.transaction = self._make_transaction(self.lock, self.parent, self.current_time)
self.dependency = self._make_dependency()
def _make_transaction(self, lock, parent, current_time_accessor):
raise NotImplementedError
@staticmethod
def _make_dependency():
instance = mock.Mock(spec=interfaces.IDependency)
instance.extend = mock.Mock(return_value=True)
return instance
def test_evaluate(self):
self.transaction.evaluate(self.dependency, 1)
self.lock.evaluate.assert_called_once_with(self.dependency, self.transaction, 1)
def test_get_session_id(self):
session1_id = self.transaction.get_session_id()
session2_id = self.transaction.get_session_id()
self.assertEqual(session1_id, session2_id)
self.assertIsInstance(session2_id, string_types)
def run(self, result=None):
if self.__class__.__name__.startswith('Abstract'):
return
super(AbstractTransactionTestCase, self).run(result)
class TransactionTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
class Transaction(transaction.Transaction):
_current_time = current_time_accessor
return Transaction(lock)
def test_parent(self):
self.assertIsNone(self.transaction.parent())
def test_get_start_time(self):
self.current_time.reset_mock()
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_start_time(), initial_return_value)
self.current_time.assert_not_called()
def test_get_end_time(self):
self.current_time.reset_mock()
with self.assertRaises(RuntimeError):
self.transaction.get_end_time()
self.current_time.return_value += 1
self.transaction.finish()
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_end_time(), initial_return_value)
self.current_time.assert_called_once_with()
def test_add_dependency_and_finish(self):
dependency1 = self._make_dependency()
dependency1.id = 1
dependency2 = self._make_dependency()
dependency2.id = 2
dependency3 = self._make_dependency()
dependency3.id = 3
self.transaction.add_dependency(dependency1, None)
self.lock.acquire.assert_called_once_with(dependency1, self.transaction, None)
self.lock.reset_mock()
self.transaction.add_dependency(dependency2, None)
self.lock.acquire.assert_called_once_with(dependency2, self.transaction, None)
self.lock.reset_mock()
dependency1.extend.assert_called_once_with(dependency2)
dependency1.reset_mock()
self.transaction.add_dependency(dependency3, 1)
self.lock.acquire.assert_called_once_with(dependency3, self.transaction, 1)
self.lock.reset_mock()
dependency1.extend.assert_not_called()
self.transaction.finish()
self.assertEqual(self.lock.release.call_count, 2)
args, kwargs = self.lock.release.call_args_list[-1]
self.assertEqual(len(args[0].delegates), 1)
self.assertEqual(args[0].delegates[0].id, 1)
self.assertIs(args[1], self.transaction)
self.assertIsNone(args[2])
args, kwargs = self.lock.release.call_args_list[-2]
self.assertEqual(len(args[0].delegates), 1)
self.assertEqual(args[0].delegates[0].id, 3)
self.assertIs(args[1], self.transaction)
self.assertEqual(args[2], 1)
def test_bool(self):
self.assertTrue(self.transaction)
class SavePointTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
return transaction.SavePoint(lock, parent)
def test_parent(self):
self.assertIs(self.transaction.parent(), self.parent)
def test_get_start_time(self):
self.transaction.get_start_time()
self.parent.get_start_time.assert_called_once_with()
def test_get_end_time(self):
self.transaction.get_end_time()
self.parent.get_end_time.assert_called_once_with()
def test_add_dependency(self):
self.transaction.add_dependency(self.dependency, 1)
self.lock.acquire.assert_called_once_with(self.dependency, self.transaction, 1)
self.parent.add_dependency.assert_called_once_with(self.dependency, 1)
def test_bool(self):
self.assertTrue(self.transaction)
class DummyTransactionTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
class DummyTransaction(transaction.DummyTransaction):
_current_time = current_time_accessor
return DummyTransaction(lock)
def test_parent(self):
self.assertIsNone(self.transaction.parent())
def test_get_start_time(self):
self.current_time.reset_mock()
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
self.assertEqual(self.current_time.call_count, 2)
def test_get_end_time(self):
self.current_time.reset_mock()
self.current_time.return_value += 1
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
self.assertEqual(self.current_time.call_count, 2)
def test_bool(self):
self.assertFalse(self.transaction)
class TransactionManagerTestCase(unittest.TestCase):
def setUp(self):
self.transaction = mock.Mock(spec=interfaces.ITransaction)
self.lock = mock.Mock(spec=interfaces.IDependency)
self.transaction_manager = transaction.TransactionManager(self.lock)
def test_current_none(self):
current_transaction = self.transaction_manager.current()
self.assertIsInstance(current_transaction, transaction.DummyTransaction)
def test_current_set_get(self):
self.transaction_manager.current(self.transaction)
self.assertIs(self.transaction_manager.current(), self.transaction)
def test_begin(self):
initial_transaction = self.transaction_manager.begin()
self.assertIsInstance(initial_transaction, transaction.Transaction)
save_point = self.transaction_manager.begin()
self.assertIsInstance(save_point, transaction.SavePoint)
self.assertIs(save_point.parent(), initial_transaction)
nested_save_point = self.transaction_manager.begin()
self.assertIsInstance(nested_save_point, transaction.SavePoint)
self.assertIs(nested_save_point.parent(), save_point)
def test_finish_delegate_transaction(self):
self.transaction_manager.current(self.transaction)
self.transaction_manager.finish()
self.transaction.finish.assert_called_once_with()
def test_finish_transaction(self):
self.transaction_manager.begin()
self.transaction_manager.finish()
self.assertIsInstance(self.transaction_manager.current(), transaction.DummyTransaction)
def test_finish_savepoint(self):
initial_transaction = self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.finish()
self.assertIs(self.transaction_manager.current(), initial_transaction)
def test_flush(self):
self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.flush()
self.assertIsInstance(self.transaction_manager.current(), transaction.DummyTransaction)
| true | true |
f72c31f2bcdc0ad3367f05a6e93c9a41b1a34424 | 1,886 | py | Python | src/oci/data_labeling_service_dataplane/models/text_dataset_format_details.py | ezequielramos/oci-python-sdk | cc4235cf217beaf9feed75760e9ce82610222762 | [
"Apache-2.0",
"BSD-3-Clause"
] | 249 | 2017-09-11T22:06:05.000Z | 2022-03-04T17:09:29.000Z | src/oci/data_labeling_service_dataplane/models/text_dataset_format_details.py | ezequielramos/oci-python-sdk | cc4235cf217beaf9feed75760e9ce82610222762 | [
"Apache-2.0",
"BSD-3-Clause"
] | 228 | 2017-09-11T23:07:26.000Z | 2022-03-23T10:58:50.000Z | src/oci/data_labeling_service_dataplane/models/text_dataset_format_details.py | ezequielramos/oci-python-sdk | cc4235cf217beaf9feed75760e9ce82610222762 | [
"Apache-2.0",
"BSD-3-Clause"
] | 224 | 2017-09-27T07:32:43.000Z | 2022-03-25T16:55:42.000Z | # coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from .dataset_format_details import DatasetFormatDetails
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class TextDatasetFormatDetails(DatasetFormatDetails):
"""
Indicates the dataset is comprised of txt files.
"""
def __init__(self, **kwargs):
"""
Initializes a new TextDatasetFormatDetails object with values from keyword arguments. The default value of the :py:attr:`~oci.data_labeling_service_dataplane.models.TextDatasetFormatDetails.format_type` attribute
of this class is ``TEXT`` and it should not be changed.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param format_type:
The value to assign to the format_type property of this TextDatasetFormatDetails.
Allowed values for this property are: "DOCUMENT", "IMAGE", "TEXT"
:type format_type: str
"""
self.swagger_types = {
'format_type': 'str'
}
self.attribute_map = {
'format_type': 'formatType'
}
self._format_type = None
self._format_type = 'TEXT'
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| 37.72 | 245 | 0.697243 |
from .dataset_format_details import DatasetFormatDetails
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class TextDatasetFormatDetails(DatasetFormatDetails):
def __init__(self, **kwargs):
self.swagger_types = {
'format_type': 'str'
}
self.attribute_map = {
'format_type': 'formatType'
}
self._format_type = None
self._format_type = 'TEXT'
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f72c32112bb05acf4043ba5c15ccde4c05c4d6f3 | 24,352 | py | Python | compiler/characterizer/model_check.py | ycyang0508/OpenRAM | 54c6043cb81c51f5f4a2f77e91145545ce0ed6d6 | [
"BSD-3-Clause"
] | 1 | 2022-02-17T22:12:46.000Z | 2022-02-17T22:12:46.000Z | compiler/characterizer/model_check.py | ycyang0508/OpenRAM | 54c6043cb81c51f5f4a2f77e91145545ce0ed6d6 | [
"BSD-3-Clause"
] | null | null | null | compiler/characterizer/model_check.py | ycyang0508/OpenRAM | 54c6043cb81c51f5f4a2f77e91145545ce0ed6d6 | [
"BSD-3-Clause"
] | null | null | null | # See LICENSE for licensing information.
#
# Copyright (c) 2016-2021 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
import sys,re,shutil
import debug
import tech
import math
from .stimuli import *
from .trim_spice import *
from .charutils import *
import utils
from globals import OPTS
from .delay import delay
from .measurements import *
class model_check(delay):
"""Functions to test for the worst case delay in a target SRAM
The current worst case determines a feasible period for the SRAM then tests
several bits and record the delay and differences between the bits.
"""
def __init__(self, sram, spfile, corner, custom_delaychain=False):
super().__init__(sram, spfile, corner)
self.period = tech.spice["feasible_period"]
self.create_data_names()
self.custom_delaychain=custom_delaychain
def create_data_names(self):
self.wl_meas_name, self.wl_model_name = "wl_measures", "wl_model"
self.sae_meas_name, self.sae_model_name = "sae_measures", "sae_model"
self.wl_slew_name, self.sae_slew_name = "wl_slews", "sae_slews"
self.bl_meas_name, self.bl_slew_name = "bl_measures", "bl_slews"
self.power_name = "total_power"
def create_measurement_names(self, port):
"""Create measurement names. The names themselves currently define the type of measurement"""
#Create delay measurement names
wl_en_driver_delay_names = ["delay_wl_en_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_delay_names = ["delay_wl_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_delay_names = ["delay_sen_dvr_{}".format(stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
dc_delay_names = ['delay_dc_out_final']
else:
dc_delay_names = ["delay_delay_chain_stage_{}".format(stage) for stage in range(1,self.get_num_delay_stages()+1)]
self.wl_delay_meas_names = wl_en_driver_delay_names+["delay_wl_en", "delay_wl_bar"]+wl_driver_delay_names+["delay_wl"]
if port not in self.sram.readonly_ports:
self.rbl_delay_meas_names = ["delay_gated_clk_nand", "delay_delay_chain_in"]+dc_delay_names
else:
self.rbl_delay_meas_names = ["delay_gated_clk_nand"]+dc_delay_names
self.sae_delay_meas_names = ["delay_pre_sen"]+sen_driver_delay_names+["delay_sen"]
# if self.custom_delaychain:
# self.delay_chain_indices = (len(self.rbl_delay_meas_names), len(self.rbl_delay_meas_names)+1)
# else:
self.delay_chain_indices = (len(self.rbl_delay_meas_names)-len(dc_delay_names), len(self.rbl_delay_meas_names))
#Create slew measurement names
wl_en_driver_slew_names = ["slew_wl_en_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_slew_names = ["slew_wl_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_slew_names = ["slew_sen_dvr_{}".format(stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
dc_slew_names = ['slew_dc_out_final']
else:
dc_slew_names = ["slew_delay_chain_stage_{}".format(stage) for stage in range(1,self.get_num_delay_stages()+1)]
self.wl_slew_meas_names = ["slew_wl_gated_clk_bar"]+wl_en_driver_slew_names+["slew_wl_en", "slew_wl_bar"]+wl_driver_slew_names+["slew_wl"]
if port not in self.sram.readonly_ports:
self.rbl_slew_meas_names = ["slew_rbl_gated_clk_bar","slew_gated_clk_nand", "slew_delay_chain_in"]+dc_slew_names
else:
self.rbl_slew_meas_names = ["slew_rbl_gated_clk_bar"]+dc_slew_names
self.sae_slew_meas_names = ["slew_replica_bl0", "slew_pre_sen"]+sen_driver_slew_names+["slew_sen"]
self.bitline_meas_names = ["delay_wl_to_bl", "delay_bl_to_dout"]
self.power_meas_names = ['read0_power']
def create_signal_names(self, port):
"""Creates list of the signal names used in the spice file along the wl and sen paths.
Names are re-harded coded here; i.e. the names are hardcoded in most of OpenRAM and are
replicated here.
"""
delay.create_signal_names(self)
#Signal names are all hardcoded, need to update to make it work for probe address and different configurations.
wl_en_driver_signals = ["Xsram.Xcontrol{}.Xbuf_wl_en.Zb{}_int".format('{}', stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_signals = ["Xsram.Xbank0.Xwordline_driver{}.Xwl_driver_inv{}.Zb{}_int".format('{}', self.wordline_row, stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_signals = ["Xsram.Xcontrol{}.Xbuf_s_en.Zb{}_int".format('{}',stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
delay_chain_signal_names = []
else:
delay_chain_signal_names = ["Xsram.Xcontrol{}.Xreplica_bitline.Xdelay_chain.dout_{}".format('{}', stage) for stage in range(1,self.get_num_delay_stages())]
if len(self.sram.all_ports) > 1:
port_format = '{}'
else:
port_format = ''
self.wl_signal_names = ["Xsram.Xcontrol{}.gated_clk_bar".format('{}')]+\
wl_en_driver_signals+\
["Xsram.wl_en{}".format('{}'), "Xsram.Xbank0.Xwordline_driver{}.wl_bar_{}".format('{}',self.wordline_row)]+\
wl_driver_signals+\
["Xsram.Xbank0.wl{}_{}".format(port_format, self.wordline_row)]
pre_delay_chain_names = ["Xsram.Xcontrol{}.gated_clk_bar".format('{}')]
if port not in self.sram.readonly_ports:
pre_delay_chain_names+= ["Xsram.Xcontrol{}.Xand2_rbl_in.zb_int".format('{}'), "Xsram.Xcontrol{}.rbl_in".format('{}')]
self.rbl_en_signal_names = pre_delay_chain_names+\
delay_chain_signal_names+\
["Xsram.Xcontrol{}.Xreplica_bitline.delayed_en".format('{}')]
self.sae_signal_names = ["Xsram.Xcontrol{}.Xreplica_bitline.bl0_0".format('{}'), "Xsram.Xcontrol{}.pre_s_en".format('{}')]+\
sen_driver_signals+\
["Xsram.s_en{}".format('{}')]
dout_name = "{0}{1}_{2}".format(self.dout_name,"{}",self.probe_data) #Empty values are the port and probe data bit
self.bl_signal_names = ["Xsram.Xbank0.wl{}_{}".format(port_format, self.wordline_row),\
"Xsram.Xbank0.bl{}_{}".format(port_format, self.bitline_column),\
dout_name]
def create_measurement_objects(self):
"""Create the measurements used for read and write ports"""
self.create_wordline_meas_objs()
self.create_sae_meas_objs()
self.create_bl_meas_objs()
self.create_power_meas_objs()
self.all_measures = self.wl_meas_objs+self.sae_meas_objs+self.bl_meas_objs+self.power_meas_objs
def create_power_meas_objs(self):
"""Create power measurement object. Only one."""
self.power_meas_objs = []
self.power_meas_objs.append(power_measure(self.power_meas_names[0], "FALL", measure_scale=1e3))
def create_wordline_meas_objs(self):
"""Create the measurements to measure the wordline path from the gated_clk_bar signal"""
self.wl_meas_objs = []
trig_dir = "RISE"
targ_dir = "FALL"
for i in range(1, len(self.wl_signal_names)):
self.wl_meas_objs.append(delay_measure(self.wl_delay_meas_names[i-1],
self.wl_signal_names[i-1],
self.wl_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.wl_meas_objs.append(slew_measure(self.wl_slew_meas_names[i-1],
self.wl_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
self.wl_meas_objs.append(slew_measure(self.wl_slew_meas_names[-1], self.wl_signal_names[-1], trig_dir, measure_scale=1e9))
def create_bl_meas_objs(self):
"""Create the measurements to measure the bitline to dout, static stages"""
#Bitline has slightly different measurements, objects appends hardcoded.
self.bl_meas_objs = []
trig_dir, targ_dir = "RISE", "FALL" #Only check read 0
self.bl_meas_objs.append(delay_measure(self.bitline_meas_names[0],
self.bl_signal_names[0],
self.bl_signal_names[-1],
trig_dir,
targ_dir,
measure_scale=1e9))
def create_sae_meas_objs(self):
"""Create the measurements to measure the sense amp enable path from the gated_clk_bar signal. The RBL splits this path into two."""
self.sae_meas_objs = []
trig_dir = "RISE"
targ_dir = "FALL"
#Add measurements from gated_clk_bar to RBL
for i in range(1, len(self.rbl_en_signal_names)):
self.sae_meas_objs.append(delay_measure(self.rbl_delay_meas_names[i-1],
self.rbl_en_signal_names[i-1],
self.rbl_en_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.sae_meas_objs.append(slew_measure(self.rbl_slew_meas_names[i-1],
self.rbl_en_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
if self.custom_delaychain: #Hack for custom delay chains
self.sae_meas_objs[-2] = delay_measure(self.rbl_delay_meas_names[-1],
self.rbl_en_signal_names[-2],
self.rbl_en_signal_names[-1],
"RISE",
"RISE",
measure_scale=1e9)
self.sae_meas_objs.append(slew_measure(self.rbl_slew_meas_names[-1],
self.rbl_en_signal_names[-1],
trig_dir,
measure_scale=1e9))
#Add measurements from rbl_out to sae. Trigger directions do not invert from previous stage due to RBL.
trig_dir = "FALL"
targ_dir = "RISE"
for i in range(1, len(self.sae_signal_names)):
self.sae_meas_objs.append(delay_measure(self.sae_delay_meas_names[i-1],
self.sae_signal_names[i-1],
self.sae_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.sae_meas_objs.append(slew_measure(self.sae_slew_meas_names[i-1],
self.sae_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
self.sae_meas_objs.append(slew_measure(self.sae_slew_meas_names[-1],
self.sae_signal_names[-1],
trig_dir,
measure_scale=1e9))
def write_delay_measures(self):
"""
Write the measure statements to quantify the delay and power results for all targeted ports.
"""
self.sf.write("\n* Measure statements for delay and power\n")
# Output some comments to aid where cycles start and what is happening
for comment in self.cycle_comments:
self.sf.write("* {}\n".format(comment))
for read_port in self.targ_read_ports:
self.write_measures_read_port(read_port)
def get_delay_measure_variants(self, port, measure_obj):
"""Get the measurement values that can either vary from simulation to simulation (vdd, address)
or port to port (time delays)"""
#Return value is intended to match the delay measure format: trig_td, targ_td, vdd, port
#Assuming only read 0 for now
debug.info(3,"Power measurement={}".format(measure_obj))
if (type(measure_obj) is delay_measure or type(measure_obj) is slew_measure):
meas_cycle_delay = self.cycle_times[self.measure_cycles[port]["read0"]] + self.period/2
return (meas_cycle_delay, meas_cycle_delay, self.vdd_voltage, port)
elif type(measure_obj) is power_measure:
return self.get_power_measure_variants(port, measure_obj, "read")
else:
debug.error("Measurement not recognized by the model checker.",1)
def get_power_measure_variants(self, port, power_obj, operation):
"""Get the measurement values that can either vary port to port (time delays)"""
#Return value is intended to match the power measure format: t_initial, t_final, port
t_initial = self.cycle_times[self.measure_cycles[port]["read0"]]
t_final = self.cycle_times[self.measure_cycles[port]["read0"]+1]
return (t_initial, t_final, port)
def write_measures_read_port(self, port):
"""
Write the measure statements for all nodes along the wordline path.
"""
# add measure statements for delays/slews
for measure in self.all_measures:
measure_variant_inp_tuple = self.get_delay_measure_variants(port, measure)
measure.write_measure(self.stim, measure_variant_inp_tuple)
def get_measurement_values(self, meas_objs, port):
"""Gets the delays and slews from a specified port from the spice output file and returns them as lists."""
delay_meas_list = []
slew_meas_list = []
power_meas_list=[]
for measure in meas_objs:
measure_value = measure.retrieve_measure(port=port)
if type(measure_value) != float:
debug.error("Failed to Measure Value:\n\t\t{}={}".format(measure.name, measure_value),1)
if type(measure) is delay_measure:
delay_meas_list.append(measure_value)
elif type(measure)is slew_measure:
slew_meas_list.append(measure_value)
elif type(measure)is power_measure:
power_meas_list.append(measure_value)
else:
debug.error("Measurement object not recognized.",1)
return delay_meas_list, slew_meas_list,power_meas_list
def run_delay_simulation(self):
"""
This tries to simulate a period and checks if the result works. If
so, it returns True and the delays, slews, and powers. It
works on the trimmed netlist by default, so powers do not
include leakage of all cells.
"""
#Sanity Check
debug.check(self.period > 0, "Target simulation period non-positive")
wl_delay_result = [[] for i in self.all_ports]
wl_slew_result = [[] for i in self.all_ports]
sae_delay_result = [[] for i in self.all_ports]
sae_slew_result = [[] for i in self.all_ports]
bl_delay_result = [[] for i in self.all_ports]
bl_slew_result = [[] for i in self.all_ports]
power_result = [[] for i in self.all_ports]
# Checking from not data_value to data_value
self.write_delay_stimulus()
self.stim.run_sim() #running sim prodoces spice output file.
#Retrieve the results from the output file
for port in self.targ_read_ports:
#Parse and check the voltage measurements
wl_delay_result[port], wl_slew_result[port],_ = self.get_measurement_values(self.wl_meas_objs, port)
sae_delay_result[port], sae_slew_result[port],_ = self.get_measurement_values(self.sae_meas_objs, port)
bl_delay_result[port], bl_slew_result[port],_ = self.get_measurement_values(self.bl_meas_objs, port)
_,__,power_result[port] = self.get_measurement_values(self.power_meas_objs, port)
return (True,wl_delay_result, sae_delay_result, wl_slew_result, sae_slew_result, bl_delay_result, bl_slew_result, power_result)
def get_model_delays(self, port):
"""Get model delays based on port. Currently assumes single RW port."""
return self.sram.control_logic_rw.get_wl_sen_delays()
def get_num_delay_stages(self):
"""Gets the number of stages in the delay chain from the control logic"""
return len(self.sram.control_logic_rw.replica_bitline.delay_fanout_list)
def get_num_delay_fanout_list(self):
"""Gets the number of stages in the delay chain from the control logic"""
return self.sram.control_logic_rw.replica_bitline.delay_fanout_list
def get_num_delay_stage_fanout(self):
"""Gets fanout in each stage in the delay chain. Assumes each stage is the same"""
return self.sram.control_logic_rw.replica_bitline.delay_fanout_list[0]
def get_num_wl_en_driver_stages(self):
"""Gets the number of stages in the wl_en driver from the control logic"""
return self.sram.control_logic_rw.wl_en_driver.num_stages
def get_num_sen_driver_stages(self):
"""Gets the number of stages in the sen driver from the control logic"""
return self.sram.control_logic_rw.s_en_driver.num_stages
def get_num_wl_driver_stages(self):
"""Gets the number of stages in the wordline driver from the control logic"""
return self.sram.bank.wordline_driver.inv.num_stages
def scale_delays(self, delay_list):
"""Takes in a list of measured delays and convert it to simple units to easily compare to model values."""
converted_values = []
#Calculate average
total = 0
for meas_value in delay_list:
total+=meas_value
average = total/len(delay_list)
#Convert values
for meas_value in delay_list:
converted_values.append(meas_value/average)
return converted_values
def min_max_normalization(self, value_list):
"""Re-scales input values on a range from 0-1 where min(list)=0, max(list)=1"""
scaled_values = []
min_max_diff = max(value_list) - min(value_list)
average = sum(value_list)/len(value_list)
for value in value_list:
scaled_values.append((value-average)/(min_max_diff))
return scaled_values
def calculate_error_l2_norm(self, list_a, list_b):
"""Calculates error between two lists using the l2 norm"""
error_list = []
for val_a, val_b in zip(list_a, list_b):
error_list.append((val_a-val_b)**2)
return error_list
def compare_measured_and_model(self, measured_vals, model_vals):
"""First scales both inputs into similar ranges and then compares the error between both."""
scaled_meas = self.min_max_normalization(measured_vals)
debug.info(1, "Scaled measurements:\n{}".format(scaled_meas))
scaled_model = self.min_max_normalization(model_vals)
debug.info(1, "Scaled model:\n{}".format(scaled_model))
errors = self.calculate_error_l2_norm(scaled_meas, scaled_model)
debug.info(1, "Errors:\n{}\n".format(errors))
def analyze(self, probe_address, probe_data, slews, loads, port):
"""Measures entire delay path along the wordline and sense amp enable and compare it to the model delays."""
self.load=max(loads)
self.slew=max(slews)
self.set_probe(probe_address, probe_data)
self.create_signal_names(port)
self.create_measurement_names(port)
self.create_measurement_objects()
data_dict = {}
read_port = self.read_ports[0] #only test the first read port
read_port = port
self.targ_read_ports = [read_port]
self.targ_write_ports = [self.write_ports[0]]
debug.info(1,"Model test: corner {}".format(self.corner))
(success, wl_delays, sae_delays, wl_slews, sae_slews, bl_delays, bl_slews, powers)=self.run_delay_simulation()
debug.check(success, "Model measurements Failed: period={}".format(self.period))
debug.info(1,"Measured Wordline delays (ns):\n\t {}".format(wl_delays[read_port]))
debug.info(1,"Measured Wordline slews:\n\t {}".format(wl_slews[read_port]))
debug.info(1,"Measured SAE delays (ns):\n\t {}".format(sae_delays[read_port]))
debug.info(1,"Measured SAE slews:\n\t {}".format(sae_slews[read_port]))
debug.info(1,"Measured Bitline delays (ns):\n\t {}".format(bl_delays[read_port]))
data_dict[self.wl_meas_name] = wl_delays[read_port]
data_dict[self.sae_meas_name] = sae_delays[read_port]
data_dict[self.wl_slew_name] = wl_slews[read_port]
data_dict[self.sae_slew_name] = sae_slews[read_port]
data_dict[self.bl_meas_name] = bl_delays[read_port]
data_dict[self.power_name] = powers[read_port]
if OPTS.auto_delay_chain_sizing: #Model is not used in this case
wl_model_delays, sae_model_delays = self.get_model_delays(read_port)
debug.info(1,"Wordline model delays:\n\t {}".format(wl_model_delays))
debug.info(1,"SAE model delays:\n\t {}".format(sae_model_delays))
data_dict[self.wl_model_name] = wl_model_delays
data_dict[self.sae_model_name] = sae_model_delays
#Some evaluations of the model and measured values
# debug.info(1, "Comparing wordline measurements and model.")
# self.compare_measured_and_model(wl_delays[read_port], wl_model_delays)
# debug.info(1, "Comparing SAE measurements and model")
# self.compare_measured_and_model(sae_delays[read_port], sae_model_delays)
return data_dict
def get_all_signal_names(self):
"""Returns all signals names as a dict indexed by hardcoded names. Useful for writing the head of the CSV."""
name_dict = {}
#Signal names are more descriptive than the measurement names, first value trimmed to match size of measurements names.
name_dict[self.wl_meas_name] = self.wl_signal_names[1:]
name_dict[self.sae_meas_name] = self.rbl_en_signal_names[1:]+self.sae_signal_names[1:]
name_dict[self.wl_slew_name] = self.wl_slew_meas_names
name_dict[self.sae_slew_name] = self.rbl_slew_meas_names+self.sae_slew_meas_names
name_dict[self.bl_meas_name] = self.bitline_meas_names[0:1]
name_dict[self.power_name] = self.power_meas_names
#name_dict[self.wl_slew_name] = self.wl_slew_meas_names
if OPTS.auto_delay_chain_sizing:
name_dict[self.wl_model_name] = name_dict["wl_measures"] #model uses same names as measured.
name_dict[self.sae_model_name] = name_dict["sae_measures"]
return name_dict
| 54.115556 | 182 | 0.627217 |
import sys,re,shutil
import debug
import tech
import math
from .stimuli import *
from .trim_spice import *
from .charutils import *
import utils
from globals import OPTS
from .delay import delay
from .measurements import *
class model_check(delay):
def __init__(self, sram, spfile, corner, custom_delaychain=False):
super().__init__(sram, spfile, corner)
self.period = tech.spice["feasible_period"]
self.create_data_names()
self.custom_delaychain=custom_delaychain
def create_data_names(self):
self.wl_meas_name, self.wl_model_name = "wl_measures", "wl_model"
self.sae_meas_name, self.sae_model_name = "sae_measures", "sae_model"
self.wl_slew_name, self.sae_slew_name = "wl_slews", "sae_slews"
self.bl_meas_name, self.bl_slew_name = "bl_measures", "bl_slews"
self.power_name = "total_power"
def create_measurement_names(self, port):
wl_en_driver_delay_names = ["delay_wl_en_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_delay_names = ["delay_wl_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_delay_names = ["delay_sen_dvr_{}".format(stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
dc_delay_names = ['delay_dc_out_final']
else:
dc_delay_names = ["delay_delay_chain_stage_{}".format(stage) for stage in range(1,self.get_num_delay_stages()+1)]
self.wl_delay_meas_names = wl_en_driver_delay_names+["delay_wl_en", "delay_wl_bar"]+wl_driver_delay_names+["delay_wl"]
if port not in self.sram.readonly_ports:
self.rbl_delay_meas_names = ["delay_gated_clk_nand", "delay_delay_chain_in"]+dc_delay_names
else:
self.rbl_delay_meas_names = ["delay_gated_clk_nand"]+dc_delay_names
self.sae_delay_meas_names = ["delay_pre_sen"]+sen_driver_delay_names+["delay_sen"]
self.delay_chain_indices = (len(self.rbl_delay_meas_names)-len(dc_delay_names), len(self.rbl_delay_meas_names))
wl_en_driver_slew_names = ["slew_wl_en_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_slew_names = ["slew_wl_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_slew_names = ["slew_sen_dvr_{}".format(stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
dc_slew_names = ['slew_dc_out_final']
else:
dc_slew_names = ["slew_delay_chain_stage_{}".format(stage) for stage in range(1,self.get_num_delay_stages()+1)]
self.wl_slew_meas_names = ["slew_wl_gated_clk_bar"]+wl_en_driver_slew_names+["slew_wl_en", "slew_wl_bar"]+wl_driver_slew_names+["slew_wl"]
if port not in self.sram.readonly_ports:
self.rbl_slew_meas_names = ["slew_rbl_gated_clk_bar","slew_gated_clk_nand", "slew_delay_chain_in"]+dc_slew_names
else:
self.rbl_slew_meas_names = ["slew_rbl_gated_clk_bar"]+dc_slew_names
self.sae_slew_meas_names = ["slew_replica_bl0", "slew_pre_sen"]+sen_driver_slew_names+["slew_sen"]
self.bitline_meas_names = ["delay_wl_to_bl", "delay_bl_to_dout"]
self.power_meas_names = ['read0_power']
def create_signal_names(self, port):
delay.create_signal_names(self)
wl_en_driver_signals = ["Xsram.Xcontrol{}.Xbuf_wl_en.Zb{}_int".format('{}', stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_signals = ["Xsram.Xbank0.Xwordline_driver{}.Xwl_driver_inv{}.Zb{}_int".format('{}', self.wordline_row, stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_signals = ["Xsram.Xcontrol{}.Xbuf_s_en.Zb{}_int".format('{}',stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
delay_chain_signal_names = []
else:
delay_chain_signal_names = ["Xsram.Xcontrol{}.Xreplica_bitline.Xdelay_chain.dout_{}".format('{}', stage) for stage in range(1,self.get_num_delay_stages())]
if len(self.sram.all_ports) > 1:
port_format = '{}'
else:
port_format = ''
self.wl_signal_names = ["Xsram.Xcontrol{}.gated_clk_bar".format('{}')]+\
wl_en_driver_signals+\
["Xsram.wl_en{}".format('{}'), "Xsram.Xbank0.Xwordline_driver{}.wl_bar_{}".format('{}',self.wordline_row)]+\
wl_driver_signals+\
["Xsram.Xbank0.wl{}_{}".format(port_format, self.wordline_row)]
pre_delay_chain_names = ["Xsram.Xcontrol{}.gated_clk_bar".format('{}')]
if port not in self.sram.readonly_ports:
pre_delay_chain_names+= ["Xsram.Xcontrol{}.Xand2_rbl_in.zb_int".format('{}'), "Xsram.Xcontrol{}.rbl_in".format('{}')]
self.rbl_en_signal_names = pre_delay_chain_names+\
delay_chain_signal_names+\
["Xsram.Xcontrol{}.Xreplica_bitline.delayed_en".format('{}')]
self.sae_signal_names = ["Xsram.Xcontrol{}.Xreplica_bitline.bl0_0".format('{}'), "Xsram.Xcontrol{}.pre_s_en".format('{}')]+\
sen_driver_signals+\
["Xsram.s_en{}".format('{}')]
dout_name = "{0}{1}_{2}".format(self.dout_name,"{}",self.probe_data)
self.bl_signal_names = ["Xsram.Xbank0.wl{}_{}".format(port_format, self.wordline_row),\
"Xsram.Xbank0.bl{}_{}".format(port_format, self.bitline_column),\
dout_name]
def create_measurement_objects(self):
self.create_wordline_meas_objs()
self.create_sae_meas_objs()
self.create_bl_meas_objs()
self.create_power_meas_objs()
self.all_measures = self.wl_meas_objs+self.sae_meas_objs+self.bl_meas_objs+self.power_meas_objs
def create_power_meas_objs(self):
self.power_meas_objs = []
self.power_meas_objs.append(power_measure(self.power_meas_names[0], "FALL", measure_scale=1e3))
def create_wordline_meas_objs(self):
self.wl_meas_objs = []
trig_dir = "RISE"
targ_dir = "FALL"
for i in range(1, len(self.wl_signal_names)):
self.wl_meas_objs.append(delay_measure(self.wl_delay_meas_names[i-1],
self.wl_signal_names[i-1],
self.wl_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.wl_meas_objs.append(slew_measure(self.wl_slew_meas_names[i-1],
self.wl_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
self.wl_meas_objs.append(slew_measure(self.wl_slew_meas_names[-1], self.wl_signal_names[-1], trig_dir, measure_scale=1e9))
def create_bl_meas_objs(self):
self.bl_meas_objs = []
trig_dir, targ_dir = "RISE", "FALL"
self.bl_meas_objs.append(delay_measure(self.bitline_meas_names[0],
self.bl_signal_names[0],
self.bl_signal_names[-1],
trig_dir,
targ_dir,
measure_scale=1e9))
def create_sae_meas_objs(self):
self.sae_meas_objs = []
trig_dir = "RISE"
targ_dir = "FALL"
for i in range(1, len(self.rbl_en_signal_names)):
self.sae_meas_objs.append(delay_measure(self.rbl_delay_meas_names[i-1],
self.rbl_en_signal_names[i-1],
self.rbl_en_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.sae_meas_objs.append(slew_measure(self.rbl_slew_meas_names[i-1],
self.rbl_en_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
if self.custom_delaychain:
self.sae_meas_objs[-2] = delay_measure(self.rbl_delay_meas_names[-1],
self.rbl_en_signal_names[-2],
self.rbl_en_signal_names[-1],
"RISE",
"RISE",
measure_scale=1e9)
self.sae_meas_objs.append(slew_measure(self.rbl_slew_meas_names[-1],
self.rbl_en_signal_names[-1],
trig_dir,
measure_scale=1e9))
trig_dir = "FALL"
targ_dir = "RISE"
for i in range(1, len(self.sae_signal_names)):
self.sae_meas_objs.append(delay_measure(self.sae_delay_meas_names[i-1],
self.sae_signal_names[i-1],
self.sae_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.sae_meas_objs.append(slew_measure(self.sae_slew_meas_names[i-1],
self.sae_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
self.sae_meas_objs.append(slew_measure(self.sae_slew_meas_names[-1],
self.sae_signal_names[-1],
trig_dir,
measure_scale=1e9))
def write_delay_measures(self):
self.sf.write("\n* Measure statements for delay and power\n")
for comment in self.cycle_comments:
self.sf.write("* {}\n".format(comment))
for read_port in self.targ_read_ports:
self.write_measures_read_port(read_port)
def get_delay_measure_variants(self, port, measure_obj):
debug.info(3,"Power measurement={}".format(measure_obj))
if (type(measure_obj) is delay_measure or type(measure_obj) is slew_measure):
meas_cycle_delay = self.cycle_times[self.measure_cycles[port]["read0"]] + self.period/2
return (meas_cycle_delay, meas_cycle_delay, self.vdd_voltage, port)
elif type(measure_obj) is power_measure:
return self.get_power_measure_variants(port, measure_obj, "read")
else:
debug.error("Measurement not recognized by the model checker.",1)
def get_power_measure_variants(self, port, power_obj, operation):
t_initial = self.cycle_times[self.measure_cycles[port]["read0"]]
t_final = self.cycle_times[self.measure_cycles[port]["read0"]+1]
return (t_initial, t_final, port)
def write_measures_read_port(self, port):
for measure in self.all_measures:
measure_variant_inp_tuple = self.get_delay_measure_variants(port, measure)
measure.write_measure(self.stim, measure_variant_inp_tuple)
def get_measurement_values(self, meas_objs, port):
delay_meas_list = []
slew_meas_list = []
power_meas_list=[]
for measure in meas_objs:
measure_value = measure.retrieve_measure(port=port)
if type(measure_value) != float:
debug.error("Failed to Measure Value:\n\t\t{}={}".format(measure.name, measure_value),1)
if type(measure) is delay_measure:
delay_meas_list.append(measure_value)
elif type(measure)is slew_measure:
slew_meas_list.append(measure_value)
elif type(measure)is power_measure:
power_meas_list.append(measure_value)
else:
debug.error("Measurement object not recognized.",1)
return delay_meas_list, slew_meas_list,power_meas_list
def run_delay_simulation(self):
debug.check(self.period > 0, "Target simulation period non-positive")
wl_delay_result = [[] for i in self.all_ports]
wl_slew_result = [[] for i in self.all_ports]
sae_delay_result = [[] for i in self.all_ports]
sae_slew_result = [[] for i in self.all_ports]
bl_delay_result = [[] for i in self.all_ports]
bl_slew_result = [[] for i in self.all_ports]
power_result = [[] for i in self.all_ports]
self.write_delay_stimulus()
self.stim.run_sim()
for port in self.targ_read_ports:
wl_delay_result[port], wl_slew_result[port],_ = self.get_measurement_values(self.wl_meas_objs, port)
sae_delay_result[port], sae_slew_result[port],_ = self.get_measurement_values(self.sae_meas_objs, port)
bl_delay_result[port], bl_slew_result[port],_ = self.get_measurement_values(self.bl_meas_objs, port)
_,__,power_result[port] = self.get_measurement_values(self.power_meas_objs, port)
return (True,wl_delay_result, sae_delay_result, wl_slew_result, sae_slew_result, bl_delay_result, bl_slew_result, power_result)
def get_model_delays(self, port):
return self.sram.control_logic_rw.get_wl_sen_delays()
def get_num_delay_stages(self):
return len(self.sram.control_logic_rw.replica_bitline.delay_fanout_list)
def get_num_delay_fanout_list(self):
return self.sram.control_logic_rw.replica_bitline.delay_fanout_list
def get_num_delay_stage_fanout(self):
return self.sram.control_logic_rw.replica_bitline.delay_fanout_list[0]
def get_num_wl_en_driver_stages(self):
return self.sram.control_logic_rw.wl_en_driver.num_stages
def get_num_sen_driver_stages(self):
return self.sram.control_logic_rw.s_en_driver.num_stages
def get_num_wl_driver_stages(self):
return self.sram.bank.wordline_driver.inv.num_stages
def scale_delays(self, delay_list):
converted_values = []
total = 0
for meas_value in delay_list:
total+=meas_value
average = total/len(delay_list)
for meas_value in delay_list:
converted_values.append(meas_value/average)
return converted_values
def min_max_normalization(self, value_list):
scaled_values = []
min_max_diff = max(value_list) - min(value_list)
average = sum(value_list)/len(value_list)
for value in value_list:
scaled_values.append((value-average)/(min_max_diff))
return scaled_values
def calculate_error_l2_norm(self, list_a, list_b):
error_list = []
for val_a, val_b in zip(list_a, list_b):
error_list.append((val_a-val_b)**2)
return error_list
def compare_measured_and_model(self, measured_vals, model_vals):
scaled_meas = self.min_max_normalization(measured_vals)
debug.info(1, "Scaled measurements:\n{}".format(scaled_meas))
scaled_model = self.min_max_normalization(model_vals)
debug.info(1, "Scaled model:\n{}".format(scaled_model))
errors = self.calculate_error_l2_norm(scaled_meas, scaled_model)
debug.info(1, "Errors:\n{}\n".format(errors))
def analyze(self, probe_address, probe_data, slews, loads, port):
self.load=max(loads)
self.slew=max(slews)
self.set_probe(probe_address, probe_data)
self.create_signal_names(port)
self.create_measurement_names(port)
self.create_measurement_objects()
data_dict = {}
read_port = self.read_ports[0]
read_port = port
self.targ_read_ports = [read_port]
self.targ_write_ports = [self.write_ports[0]]
debug.info(1,"Model test: corner {}".format(self.corner))
(success, wl_delays, sae_delays, wl_slews, sae_slews, bl_delays, bl_slews, powers)=self.run_delay_simulation()
debug.check(success, "Model measurements Failed: period={}".format(self.period))
debug.info(1,"Measured Wordline delays (ns):\n\t {}".format(wl_delays[read_port]))
debug.info(1,"Measured Wordline slews:\n\t {}".format(wl_slews[read_port]))
debug.info(1,"Measured SAE delays (ns):\n\t {}".format(sae_delays[read_port]))
debug.info(1,"Measured SAE slews:\n\t {}".format(sae_slews[read_port]))
debug.info(1,"Measured Bitline delays (ns):\n\t {}".format(bl_delays[read_port]))
data_dict[self.wl_meas_name] = wl_delays[read_port]
data_dict[self.sae_meas_name] = sae_delays[read_port]
data_dict[self.wl_slew_name] = wl_slews[read_port]
data_dict[self.sae_slew_name] = sae_slews[read_port]
data_dict[self.bl_meas_name] = bl_delays[read_port]
data_dict[self.power_name] = powers[read_port]
if OPTS.auto_delay_chain_sizing:
wl_model_delays, sae_model_delays = self.get_model_delays(read_port)
debug.info(1,"Wordline model delays:\n\t {}".format(wl_model_delays))
debug.info(1,"SAE model delays:\n\t {}".format(sae_model_delays))
data_dict[self.wl_model_name] = wl_model_delays
data_dict[self.sae_model_name] = sae_model_delays
return data_dict
def get_all_signal_names(self):
name_dict = {}
name_dict[self.wl_meas_name] = self.wl_signal_names[1:]
name_dict[self.sae_meas_name] = self.rbl_en_signal_names[1:]+self.sae_signal_names[1:]
name_dict[self.wl_slew_name] = self.wl_slew_meas_names
name_dict[self.sae_slew_name] = self.rbl_slew_meas_names+self.sae_slew_meas_names
name_dict[self.bl_meas_name] = self.bitline_meas_names[0:1]
name_dict[self.power_name] = self.power_meas_names
if OPTS.auto_delay_chain_sizing:
name_dict[self.wl_model_name] = name_dict["wl_measures"]
name_dict[self.sae_model_name] = name_dict["sae_measures"]
return name_dict
| true | true |
f72c33ad93ae6e46739f72e67c233be7339ce4cc | 1,937 | py | Python | .ignore/old/SDN_MininetUtils.py | souvikdas95/SDN_VideoStreaming | a75a77a1d2a087c96102b2c02f5a67d3a90f1fa2 | [
"Apache-2.0"
] | 4 | 2018-04-26T20:33:15.000Z | 2022-01-20T22:43:08.000Z | .ignore/old/SDN_MininetUtils.py | souvikdas95/SDN_VideoStreaming | a75a77a1d2a087c96102b2c02f5a67d3a90f1fa2 | [
"Apache-2.0"
] | null | null | null | .ignore/old/SDN_MininetUtils.py | souvikdas95/SDN_VideoStreaming | a75a77a1d2a087c96102b2c02f5a67d3a90f1fa2 | [
"Apache-2.0"
] | 3 | 2019-05-02T08:51:20.000Z | 2021-04-02T15:29:52.000Z | #!/usr/bin/python
import mininet.util;
from mininet.util import quietRun, moveIntf;
def _makeIntfPair( intf1, intf2, addr1=None, addr2=None, node1=None, node2=None,
deleteIntfs=True, runCmd=None ):
"""Make a veth pair connnecting new interfaces intf1 and intf2
intf1: name for interface 1
intf2: name for interface 2
addr1: MAC address for interface 1 (optional)
addr2: MAC address for interface 2 (optional)
node1: home node for interface 1 (optional)
node2: home node for interface 2 (optional)
deleteIntfs: delete intfs before creating them
runCmd: function to run shell commands (quietRun)
raises Exception on failure
Changes:
The problem here is that we can not add a link to another
netns within a Docker container since it does not know
the other process (process not found error).
So we have to do it different:
We create the veth pair inside the default netns and move them
into their netns (container) afterwards."""
if deleteIntfs:
# Delete any old interfaces with the same names
quietRun( 'ip link del ' + intf1, shell=True )
quietRun( 'ip link del ' + intf2, shell=True )
# first: create the veth pair in default namespace
if addr1 is None and addr2 is None:
cmdOutput = quietRun( 'ip link add name %s '
'type veth peer name %s ' %
( intf1, intf2 ),
shell=True )
else:
cmdOutput = quietRun( 'ip link add name %s '
'address %s '
'type veth peer name %s '
'address %s ' %
( intf1, addr1, intf2, addr2 ),
shell=True )
if cmdOutput:
raise Exception( "Error creating interface pair (%s,%s): %s " %
( intf1, intf2, cmdOutput ) )
# second: move both endpoints into the corresponding namespaces
moveIntf(intf1, node1)
moveIntf(intf2, node2)
# Override Method
mininet.util.makeIntfPair = _makeIntfPair; | 35.87037 | 81 | 0.663913 |
import mininet.util;
from mininet.util import quietRun, moveIntf;
def _makeIntfPair( intf1, intf2, addr1=None, addr2=None, node1=None, node2=None,
deleteIntfs=True, runCmd=None ):
if deleteIntfs:
quietRun( 'ip link del ' + intf1, shell=True )
quietRun( 'ip link del ' + intf2, shell=True )
if addr1 is None and addr2 is None:
cmdOutput = quietRun( 'ip link add name %s '
'type veth peer name %s ' %
( intf1, intf2 ),
shell=True )
else:
cmdOutput = quietRun( 'ip link add name %s '
'address %s '
'type veth peer name %s '
'address %s ' %
( intf1, addr1, intf2, addr2 ),
shell=True )
if cmdOutput:
raise Exception( "Error creating interface pair (%s,%s): %s " %
( intf1, intf2, cmdOutput ) )
moveIntf(intf1, node1)
moveIntf(intf2, node2)
mininet.util.makeIntfPair = _makeIntfPair; | true | true |
f72c344a4be417fe87d7e7e8ebbc0ea10789d3b1 | 22,433 | py | Python | nuitka/specs/BuiltinParameterSpecs.py | gdementen/Nuitka | 1f12be2364d07ffb168a7302dde94cb25eca9a70 | [
"Apache-2.0"
] | 5,421 | 2018-09-24T08:04:06.000Z | 2022-03-31T20:02:37.000Z | venv/Lib/site-packages/nuitka/specs/BuiltinParameterSpecs.py | matthijsvanvliet/raytracing-python | 73d692b47330ab94eedde579a51063e3a907e92b | [
"MIT"
] | 1,348 | 2018-09-22T13:41:00.000Z | 2022-03-31T22:33:40.000Z | venv/Lib/site-packages/nuitka/specs/BuiltinParameterSpecs.py | matthijsvanvliet/raytracing-python | 73d692b47330ab94eedde579a51063e3a907e92b | [
"MIT"
] | 396 | 2018-09-28T15:37:03.000Z | 2022-03-29T10:52:09.000Z | # Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Optimizations of built-ins to built-in calls.
"""
from __future__ import print_function
import math
from nuitka.__past__ import builtins
from nuitka.PythonVersions import python_version
from nuitka.Tracing import optimization_logger
from .ParameterSpecs import ParameterSpec, TooManyArguments, matchCall
class BuiltinParameterSpec(ParameterSpec):
__slots__ = ("builtin",)
def __init__(
self,
name,
arg_names,
default_count,
list_star_arg=None,
dict_star_arg=None,
pos_only_args=(),
kw_only_args=(),
):
ParameterSpec.__init__(
self,
ps_name=name,
ps_normal_args=arg_names,
ps_list_star_arg=list_star_arg,
ps_dict_star_arg=dict_star_arg,
ps_default_count=default_count,
ps_pos_only_args=pos_only_args,
ps_kw_only_args=kw_only_args,
)
self.builtin = getattr(builtins, name, None)
assert default_count <= len(arg_names) + len(kw_only_args) + len(pos_only_args)
def __repr__(self):
return "<BuiltinParameterSpec %s>" % self.name
def getName(self):
return self.name
def isCompileTimeComputable(self, values):
# By default, we make this dependent on the ability to compute the
# arguments, which is of course a good start for most cases, so this
# is for overloads, pylint: disable=no-self-use
for value in values:
if value is not None and not value.isCompileTimeConstant():
return False
return True
def simulateCall(self, given_values):
# Using star dict call for simulation and catch any exception as really
# fatal, pylint: disable=broad-except,too-many-branches
try:
given_normal_args = given_values[: self.getArgumentCount()]
if self.list_star_arg:
given_list_star_args = given_values[self.getArgumentCount()]
else:
given_list_star_args = None
if self.dict_star_arg:
given_dict_star_args = given_values[-1]
else:
given_dict_star_args = None
arg_dict = {}
for arg_name, given_value in zip(
self.getArgumentNames(), given_normal_args
):
assert type(given_value) not in (
tuple,
list,
), "do not like a tuple %s" % (given_value,)
if given_value is not None:
arg_dict[arg_name] = given_value.getCompileTimeConstant()
if given_dict_star_args:
for given_dict_star_arg in reversed(given_dict_star_args):
arg_name = given_dict_star_arg.subnode_key.getCompileTimeConstant()
arg_value = (
given_dict_star_arg.subnode_value.getCompileTimeConstant()
)
arg_dict[arg_name] = arg_value
arg_list = []
for arg_name in self.getArgumentNames():
if arg_name not in arg_dict:
break
arg_list.append(arg_dict[arg_name])
del arg_dict[arg_name]
except Exception as e:
optimization_logger.sysexit_exception("Fatal optimization problem", e)
if given_list_star_args:
return self.builtin(
*(
arg_list
+ list(
value.getCompileTimeConstant() for value in given_list_star_args
)
),
**arg_dict
)
else:
return self.builtin(*arg_list, **arg_dict)
class BuiltinParameterSpecNoKeywords(BuiltinParameterSpec):
__slots__ = ()
def allowsKeywords(self):
return False
def simulateCall(self, given_values):
# Using star dict call for simulation and catch any exception as really fatal,
# pylint: disable=broad-except
try:
if self.list_star_arg:
given_list_star_arg = given_values[self.getArgumentCount()]
else:
given_list_star_arg = None
arg_list = []
refuse_more = False
for _arg_name, given_value in zip(self.getArgumentNames(), given_values):
assert type(given_value) not in (
tuple,
list,
), "do not like tuple %s" % (given_value,)
if given_value is not None:
if not refuse_more:
arg_list.append(given_value.getCompileTimeConstant())
else:
assert False
else:
refuse_more = True
if given_list_star_arg is not None:
arg_list += [
value.getCompileTimeConstant() for value in given_list_star_arg
]
except Exception as e:
optimization_logger.sysexit_exception("matching call", e)
return self.builtin(*arg_list)
class BuiltinParameterSpecExceptionsKwOnly(BuiltinParameterSpec):
def __init__(self, exception_name, kw_only_args):
BuiltinParameterSpec.__init__(
self,
name=exception_name,
arg_names=(),
default_count=len(kw_only_args), # For exceptions, they will be required.
list_star_arg="args",
kw_only_args=kw_only_args,
)
class BuiltinParameterSpecExceptions(BuiltinParameterSpec):
def __init__(self, exception_name):
BuiltinParameterSpec.__init__(
self,
name=exception_name,
arg_names=(),
default_count=0,
list_star_arg="args",
)
def allowsKeywords(self):
return False
def getKeywordRefusalText(self):
return "exceptions.%s does not take keyword arguments" % self.name
def getCallableName(self):
return "exceptions." + self.getName()
def makeBuiltinExceptionParameterSpec(exception_name):
"""Factory function to create parameter spec for an exception from its name.
Args:
exception_name - (str) name of the built-in exception
Returns:
ParameterSpec that can be used to evaluate calls of these exceptions.
"""
if exception_name == "ImportError" and python_version >= 0x300:
# This is currently the only known built-in exception that does it, but let's
# be general, as surely that list is going to expand only.
return BuiltinParameterSpecExceptionsKwOnly(
exception_name=exception_name, kw_only_args=("name", "path")
)
else:
return BuiltinParameterSpecExceptions(exception_name=exception_name)
class BuiltinParameterSpecPosArgs(BuiltinParameterSpec):
def __init__(
self,
name,
pos_only_args,
arg_names,
default_count,
list_star_arg=None,
dict_star_arg=None,
):
BuiltinParameterSpec.__init__(
self,
name=name,
arg_names=arg_names,
default_count=default_count,
pos_only_args=pos_only_args,
list_star_arg=list_star_arg,
dict_star_arg=dict_star_arg,
)
if python_version < 0x370:
builtin_int_spec = BuiltinParameterSpec("int", ("x", "base"), default_count=2)
else:
builtin_int_spec = BuiltinParameterSpecPosArgs(
"int", ("x",), ("base",), default_count=2
)
# These builtins are only available for Python2
if python_version < 0x300:
builtin_long_spec = BuiltinParameterSpec("long", ("x", "base"), default_count=2)
builtin_execfile_spec = BuiltinParameterSpecNoKeywords(
"execfile", ("filename", "globals", "locals"), default_count=2
)
builtin_unicode_p2_spec = BuiltinParameterSpec(
"unicode", ("string", "encoding", "errors"), default_count=3
)
builtin_xrange_spec = BuiltinParameterSpecNoKeywords(
"xrange" if python_version < 0x300 else "range",
("start", "stop", "step"),
default_count=2,
)
if python_version < 0x370:
builtin_bool_spec = BuiltinParameterSpec("bool", ("x",), default_count=1)
else:
builtin_bool_spec = BuiltinParameterSpecNoKeywords("bool", ("x",), default_count=1)
if python_version < 0x370:
builtin_float_spec = BuiltinParameterSpec("float", ("x",), default_count=1)
else:
builtin_float_spec = BuiltinParameterSpecNoKeywords(
"float", ("x",), default_count=1
)
builtin_complex_spec = BuiltinParameterSpec(
"complex", ("real", "imag"), default_count=2
)
# This built-in have variable parameters for Python2/3
if python_version < 0x300:
builtin_str_spec = BuiltinParameterSpec("str", ("object",), default_count=1)
else:
builtin_str_spec = BuiltinParameterSpec(
"str", ("object", "encoding", "errors"), default_count=3
)
builtin_len_spec = BuiltinParameterSpecNoKeywords("len", ("object",), default_count=0)
builtin_dict_spec = BuiltinParameterSpec(
"dict", (), default_count=0, list_star_arg="list_args", dict_star_arg="dict_args"
)
builtin_any_spec = BuiltinParameterSpecNoKeywords("any", ("object",), default_count=0)
builtin_abs_spec = BuiltinParameterSpecNoKeywords("abs", ("object",), default_count=0)
builtin_all_spec = BuiltinParameterSpecNoKeywords("all", ("object",), default_count=0)
if python_version < 0x370:
builtin_tuple_spec = BuiltinParameterSpec("tuple", ("sequence",), default_count=1)
builtin_list_spec = BuiltinParameterSpec("list", ("sequence",), default_count=1)
else:
builtin_tuple_spec = BuiltinParameterSpecNoKeywords(
"tuple", ("sequence",), default_count=1
)
builtin_list_spec = BuiltinParameterSpecNoKeywords(
"list", ("sequence",), default_count=1
)
builtin_set_spec = BuiltinParameterSpecNoKeywords("set", ("iterable",), default_count=1)
builtin_frozenset_spec = BuiltinParameterSpecNoKeywords(
"frozenset", ("iterable",), default_count=1
)
builtin_import_spec = BuiltinParameterSpec(
"__import__", ("name", "globals", "locals", "fromlist", "level"), default_count=4
)
if python_version < 0x300:
builtin_open_spec = BuiltinParameterSpec(
"open", ("name", "mode", "buffering"), default_count=3
)
else:
builtin_open_spec = BuiltinParameterSpec(
"open",
(
"file",
"mode",
"buffering",
"encoding",
"errors",
"newline",
"closefd",
"opener",
),
default_count=7,
)
builtin_chr_spec = BuiltinParameterSpecNoKeywords("chr", ("i",), default_count=0)
builtin_ord_spec = BuiltinParameterSpecNoKeywords("ord", ("c",), default_count=0)
builtin_bin_spec = BuiltinParameterSpecNoKeywords("bin", ("number",), default_count=0)
builtin_oct_spec = BuiltinParameterSpecNoKeywords("oct", ("number",), default_count=0)
builtin_hex_spec = BuiltinParameterSpecNoKeywords("hex", ("number",), default_count=0)
builtin_id_spec = BuiltinParameterSpecNoKeywords("id", ("object",), default_count=0)
builtin_repr_spec = BuiltinParameterSpecNoKeywords("repr", ("object",), default_count=0)
builtin_dir_spec = BuiltinParameterSpecNoKeywords("dir", ("object",), default_count=1)
builtin_vars_spec = BuiltinParameterSpecNoKeywords("vars", ("object",), default_count=1)
builtin_locals_spec = BuiltinParameterSpecNoKeywords("locals", (), default_count=0)
builtin_globals_spec = BuiltinParameterSpecNoKeywords("globals", (), default_count=0)
builtin_eval_spec = BuiltinParameterSpecNoKeywords(
"eval", ("source", "globals", "locals"), 2
)
if python_version < 0x300:
builtin_compile_spec = BuiltinParameterSpec(
"compile",
("source", "filename", "mode", "flags", "dont_inherit"),
default_count=2,
)
else:
builtin_compile_spec = BuiltinParameterSpec(
"compile",
("source", "filename", "mode", "flags", "dont_inherit", "optimize"),
default_count=3,
)
if python_version >= 0x300:
builtin_exec_spec = BuiltinParameterSpecNoKeywords(
"exec", ("source", "globals", "locals"), default_count=2
)
# Note: Iter in fact names its first argument if the default applies
# "collection", fixed up in a wrapper.
builtin_iter_spec = BuiltinParameterSpecNoKeywords(
"iter", ("callable", "sentinel"), default_count=1
)
builtin_next_spec = BuiltinParameterSpecNoKeywords(
"next", ("iterator", "default"), default_count=1
)
# Note: type with 1 and type with 3 arguments are too different.
builtin_type1_spec = BuiltinParameterSpecNoKeywords(
"type", ("object",), default_count=0
)
builtin_type3_spec = BuiltinParameterSpecNoKeywords(
"type", ("name", "bases", "dict"), default_count=0
)
builtin_super_spec = BuiltinParameterSpecNoKeywords(
"super", ("type", "object"), default_count=1 if python_version < 0x300 else 2
)
builtin_hasattr_spec = BuiltinParameterSpecNoKeywords(
"hasattr", ("object", "name"), default_count=0
)
builtin_getattr_spec = BuiltinParameterSpecNoKeywords(
"getattr", ("object", "name", "default"), default_count=1
)
builtin_setattr_spec = BuiltinParameterSpecNoKeywords(
"setattr", ("object", "name", "value"), default_count=0
)
builtin_isinstance_spec = BuiltinParameterSpecNoKeywords(
"isinstance", ("instance", "classes"), default_count=0
)
builtin_issubclass_spec = BuiltinParameterSpecNoKeywords(
"issubclass", ("cls", "classes"), default_count=0
)
class BuiltinBytearraySpec(BuiltinParameterSpecPosArgs):
def isCompileTimeComputable(self, values):
# For bytearrays, we need to avoid the case of large bytearray
# construction from an integer at compile time.
result = BuiltinParameterSpec.isCompileTimeComputable(self, values=values)
if result and len(values) == 1:
index_value = values[0].getIndexValue()
if index_value is None:
return result
return index_value < 256
else:
return result
builtin_bytearray_spec = BuiltinBytearraySpec(
"bytearray", ("string",), ("encoding", "errors"), default_count=2
)
builtin_bytes_p3_spec = BuiltinBytearraySpec(
"bytes", ("string",), ("encoding", "errors"), default_count=3
)
# Beware: One argument version defines "stop", not "start".
builtin_slice_spec = BuiltinParameterSpecNoKeywords(
"slice", ("start", "stop", "step"), default_count=2
)
builtin_hash_spec = BuiltinParameterSpecNoKeywords("hash", ("object",), default_count=0)
builtin_format_spec = BuiltinParameterSpecNoKeywords(
"format", ("value", "format_spec"), default_count=1
)
if python_version < 0x380:
builtin_sum_spec = BuiltinParameterSpecNoKeywords(
"sum", ("sequence", "start"), default_count=1
)
else:
builtin_sum_spec = BuiltinParameterSpecPosArgs(
"sum", ("sequence",), ("start",), default_count=1
)
builtin_staticmethod_spec = BuiltinParameterSpecNoKeywords(
"staticmethod", ("function",), default_count=0
)
builtin_classmethod_spec = BuiltinParameterSpecNoKeywords(
"classmethod", ("function",), default_count=0
)
if python_version < 0x300:
builtin_sorted_spec = BuiltinParameterSpecNoKeywords(
"sorted", ("iterable", "cmp", "key", "reverse"), default_count=2
)
else:
builtin_sorted_spec = BuiltinParameterSpecNoKeywords(
"sorted", ("iterable", "key", "reverse"), default_count=2
)
builtin_reversed_spec = BuiltinParameterSpecNoKeywords(
"reversed", ("object",), default_count=0
)
builtin_reversed_spec = BuiltinParameterSpecNoKeywords(
"reversed", ("object",), default_count=0
)
if python_version < 0x300:
builtin_enumerate_spec = BuiltinParameterSpec(
"enumerate", ("sequence", "start"), default_count=1
)
else:
builtin_enumerate_spec = BuiltinParameterSpec(
"enumerate", ("iterable", "start"), default_count=1
)
class BuiltinRangeSpec(BuiltinParameterSpecNoKeywords):
def isCompileTimeComputable(self, values):
# For ranges, we need have many cases that can prevent the ability
# to pre-compute, pylint: disable=too-many-branches,too-many-return-statements
result = BuiltinParameterSpecNoKeywords.isCompileTimeComputable(
self, values=values
)
if result:
arg_count = len(values)
if arg_count == 1:
low = values[0]
# If it's not a number constant, we can compute the exception
# that will be raised.
if not low.isNumberConstant():
return True
return low.getCompileTimeConstant() < 256
elif arg_count == 2:
low, high = values
# If it's not a number constant, we can compute the exception
# that will be raised.
if not low.isNumberConstant() or not high.isNumberConstant():
return True
return (
high.getCompileTimeConstant() - low.getCompileTimeConstant() < 256
)
elif arg_count == 3:
low, high, step = values
if (
not low.isNumberConstant()
or not high.isNumberConstant()
or not step.isNumberConstant()
):
return True
low = low.getCompileTimeConstant()
high = high.getCompileTimeConstant()
step = step.getCompileTimeConstant()
# It's going to give a ZeroDivisionError in this case.
if step == 0:
return True
if low < high:
if step < 0:
return True
else:
return math.ceil(float(high - low) / step) < 256
else:
if step > 0:
return True
else:
return math.ceil(float(high - low) / step) < 256
else:
assert False
else:
return False
builtin_range_spec = BuiltinRangeSpec(
"range", ("start", "stop", "step"), default_count=2
)
if python_version >= 0x300:
builtin_ascii_spec = BuiltinParameterSpecNoKeywords(
"ascii", ("object",), default_count=0
)
builtin_divmod_spec = BuiltinParameterSpecNoKeywords(
"divmod", ("left", "right"), default_count=0
)
def extractBuiltinArgs(node, builtin_spec, builtin_class, empty_special_class=None):
# Many cases to deal with, pylint: disable=too-many-branches
try:
kw = node.subnode_kwargs
# TODO: Could check for too many / too few, even if they are unknown, we
# might raise that error, but that need not be optimized immediately.
if kw is not None:
if not kw.isMappingWithConstantStringKeys():
return None
pairs = kw.getMappingStringKeyPairs()
if pairs and not builtin_spec.allowsKeywords():
raise TooManyArguments(TypeError(builtin_spec.getKeywordRefusalText()))
else:
pairs = ()
args = node.subnode_args
if args:
if not args.canPredictIterationValues():
return None
positional = args.getIterationValues()
else:
positional = ()
if not positional and not pairs and empty_special_class is not None:
return empty_special_class(source_ref=node.getSourceReference())
args_dict = matchCall(
func_name=builtin_spec.getName(),
args=builtin_spec.getArgumentNames(),
kw_only_args=builtin_spec.getKwOnlyParameterNames(),
star_list_arg=builtin_spec.getStarListArgumentName(),
star_dict_arg=builtin_spec.getStarDictArgumentName(),
num_defaults=builtin_spec.getDefaultCount(),
num_posonly=builtin_spec.getPosOnlyParameterCount(),
positional=positional,
pairs=pairs,
)
except TooManyArguments as e:
from nuitka.nodes.NodeMakingHelpers import (
makeRaiseExceptionReplacementExpressionFromInstance,
wrapExpressionWithSideEffects,
)
return wrapExpressionWithSideEffects(
new_node=makeRaiseExceptionReplacementExpressionFromInstance(
expression=node, exception=e.getRealException()
),
old_node=node,
side_effects=node.extractSideEffectsPreCall(),
)
# Using list reference for passing the arguments without names where it
# it possible, otherwise dictionary to make those distinuishable.
args_list = []
for argument_name in builtin_spec.getArgumentNames():
args_list.append(args_dict[argument_name])
if builtin_spec.getStarListArgumentName() is not None:
args_list.append(args_dict[builtin_spec.getStarListArgumentName()])
if builtin_spec.getStarDictArgumentName() is not None:
args_list.append(args_dict[builtin_spec.getStarDictArgumentName()])
for argument_name in builtin_spec.getKwOnlyParameterNames():
args_list.append(args_dict[argument_name])
# Using list reference for passing the arguments without names,
result = builtin_class(*args_list, source_ref=node.getSourceReference())
if python_version < 0x380:
result.setCompatibleSourceReference(node.getCompatibleSourceReference())
return result
| 33.432191 | 88 | 0.642179 |
from __future__ import print_function
import math
from nuitka.__past__ import builtins
from nuitka.PythonVersions import python_version
from nuitka.Tracing import optimization_logger
from .ParameterSpecs import ParameterSpec, TooManyArguments, matchCall
class BuiltinParameterSpec(ParameterSpec):
__slots__ = ("builtin",)
def __init__(
self,
name,
arg_names,
default_count,
list_star_arg=None,
dict_star_arg=None,
pos_only_args=(),
kw_only_args=(),
):
ParameterSpec.__init__(
self,
ps_name=name,
ps_normal_args=arg_names,
ps_list_star_arg=list_star_arg,
ps_dict_star_arg=dict_star_arg,
ps_default_count=default_count,
ps_pos_only_args=pos_only_args,
ps_kw_only_args=kw_only_args,
)
self.builtin = getattr(builtins, name, None)
assert default_count <= len(arg_names) + len(kw_only_args) + len(pos_only_args)
def __repr__(self):
return "<BuiltinParameterSpec %s>" % self.name
def getName(self):
return self.name
def isCompileTimeComputable(self, values):
for value in values:
if value is not None and not value.isCompileTimeConstant():
return False
return True
def simulateCall(self, given_values):
try:
given_normal_args = given_values[: self.getArgumentCount()]
if self.list_star_arg:
given_list_star_args = given_values[self.getArgumentCount()]
else:
given_list_star_args = None
if self.dict_star_arg:
given_dict_star_args = given_values[-1]
else:
given_dict_star_args = None
arg_dict = {}
for arg_name, given_value in zip(
self.getArgumentNames(), given_normal_args
):
assert type(given_value) not in (
tuple,
list,
), "do not like a tuple %s" % (given_value,)
if given_value is not None:
arg_dict[arg_name] = given_value.getCompileTimeConstant()
if given_dict_star_args:
for given_dict_star_arg in reversed(given_dict_star_args):
arg_name = given_dict_star_arg.subnode_key.getCompileTimeConstant()
arg_value = (
given_dict_star_arg.subnode_value.getCompileTimeConstant()
)
arg_dict[arg_name] = arg_value
arg_list = []
for arg_name in self.getArgumentNames():
if arg_name not in arg_dict:
break
arg_list.append(arg_dict[arg_name])
del arg_dict[arg_name]
except Exception as e:
optimization_logger.sysexit_exception("Fatal optimization problem", e)
if given_list_star_args:
return self.builtin(
*(
arg_list
+ list(
value.getCompileTimeConstant() for value in given_list_star_args
)
),
**arg_dict
)
else:
return self.builtin(*arg_list, **arg_dict)
class BuiltinParameterSpecNoKeywords(BuiltinParameterSpec):
__slots__ = ()
def allowsKeywords(self):
return False
def simulateCall(self, given_values):
try:
if self.list_star_arg:
given_list_star_arg = given_values[self.getArgumentCount()]
else:
given_list_star_arg = None
arg_list = []
refuse_more = False
for _arg_name, given_value in zip(self.getArgumentNames(), given_values):
assert type(given_value) not in (
tuple,
list,
), "do not like tuple %s" % (given_value,)
if given_value is not None:
if not refuse_more:
arg_list.append(given_value.getCompileTimeConstant())
else:
assert False
else:
refuse_more = True
if given_list_star_arg is not None:
arg_list += [
value.getCompileTimeConstant() for value in given_list_star_arg
]
except Exception as e:
optimization_logger.sysexit_exception("matching call", e)
return self.builtin(*arg_list)
class BuiltinParameterSpecExceptionsKwOnly(BuiltinParameterSpec):
def __init__(self, exception_name, kw_only_args):
BuiltinParameterSpec.__init__(
self,
name=exception_name,
arg_names=(),
default_count=len(kw_only_args),
list_star_arg="args",
kw_only_args=kw_only_args,
)
class BuiltinParameterSpecExceptions(BuiltinParameterSpec):
def __init__(self, exception_name):
BuiltinParameterSpec.__init__(
self,
name=exception_name,
arg_names=(),
default_count=0,
list_star_arg="args",
)
def allowsKeywords(self):
return False
def getKeywordRefusalText(self):
return "exceptions.%s does not take keyword arguments" % self.name
def getCallableName(self):
return "exceptions." + self.getName()
def makeBuiltinExceptionParameterSpec(exception_name):
if exception_name == "ImportError" and python_version >= 0x300:
# be general, as surely that list is going to expand only.
return BuiltinParameterSpecExceptionsKwOnly(
exception_name=exception_name, kw_only_args=("name", "path")
)
else:
return BuiltinParameterSpecExceptions(exception_name=exception_name)
class BuiltinParameterSpecPosArgs(BuiltinParameterSpec):
def __init__(
self,
name,
pos_only_args,
arg_names,
default_count,
list_star_arg=None,
dict_star_arg=None,
):
BuiltinParameterSpec.__init__(
self,
name=name,
arg_names=arg_names,
default_count=default_count,
pos_only_args=pos_only_args,
list_star_arg=list_star_arg,
dict_star_arg=dict_star_arg,
)
if python_version < 0x370:
builtin_int_spec = BuiltinParameterSpec("int", ("x", "base"), default_count=2)
else:
builtin_int_spec = BuiltinParameterSpecPosArgs(
"int", ("x",), ("base",), default_count=2
)
# These builtins are only available for Python2
if python_version < 0x300:
builtin_long_spec = BuiltinParameterSpec("long", ("x", "base"), default_count=2)
builtin_execfile_spec = BuiltinParameterSpecNoKeywords(
"execfile", ("filename", "globals", "locals"), default_count=2
)
builtin_unicode_p2_spec = BuiltinParameterSpec(
"unicode", ("string", "encoding", "errors"), default_count=3
)
builtin_xrange_spec = BuiltinParameterSpecNoKeywords(
"xrange" if python_version < 0x300 else "range",
("start", "stop", "step"),
default_count=2,
)
if python_version < 0x370:
builtin_bool_spec = BuiltinParameterSpec("bool", ("x",), default_count=1)
else:
builtin_bool_spec = BuiltinParameterSpecNoKeywords("bool", ("x",), default_count=1)
if python_version < 0x370:
builtin_float_spec = BuiltinParameterSpec("float", ("x",), default_count=1)
else:
builtin_float_spec = BuiltinParameterSpecNoKeywords(
"float", ("x",), default_count=1
)
builtin_complex_spec = BuiltinParameterSpec(
"complex", ("real", "imag"), default_count=2
)
# This built-in have variable parameters for Python2/3
if python_version < 0x300:
builtin_str_spec = BuiltinParameterSpec("str", ("object",), default_count=1)
else:
builtin_str_spec = BuiltinParameterSpec(
"str", ("object", "encoding", "errors"), default_count=3
)
builtin_len_spec = BuiltinParameterSpecNoKeywords("len", ("object",), default_count=0)
builtin_dict_spec = BuiltinParameterSpec(
"dict", (), default_count=0, list_star_arg="list_args", dict_star_arg="dict_args"
)
builtin_any_spec = BuiltinParameterSpecNoKeywords("any", ("object",), default_count=0)
builtin_abs_spec = BuiltinParameterSpecNoKeywords("abs", ("object",), default_count=0)
builtin_all_spec = BuiltinParameterSpecNoKeywords("all", ("object",), default_count=0)
if python_version < 0x370:
builtin_tuple_spec = BuiltinParameterSpec("tuple", ("sequence",), default_count=1)
builtin_list_spec = BuiltinParameterSpec("list", ("sequence",), default_count=1)
else:
builtin_tuple_spec = BuiltinParameterSpecNoKeywords(
"tuple", ("sequence",), default_count=1
)
builtin_list_spec = BuiltinParameterSpecNoKeywords(
"list", ("sequence",), default_count=1
)
builtin_set_spec = BuiltinParameterSpecNoKeywords("set", ("iterable",), default_count=1)
builtin_frozenset_spec = BuiltinParameterSpecNoKeywords(
"frozenset", ("iterable",), default_count=1
)
builtin_import_spec = BuiltinParameterSpec(
"__import__", ("name", "globals", "locals", "fromlist", "level"), default_count=4
)
if python_version < 0x300:
builtin_open_spec = BuiltinParameterSpec(
"open", ("name", "mode", "buffering"), default_count=3
)
else:
builtin_open_spec = BuiltinParameterSpec(
"open",
(
"file",
"mode",
"buffering",
"encoding",
"errors",
"newline",
"closefd",
"opener",
),
default_count=7,
)
builtin_chr_spec = BuiltinParameterSpecNoKeywords("chr", ("i",), default_count=0)
builtin_ord_spec = BuiltinParameterSpecNoKeywords("ord", ("c",), default_count=0)
builtin_bin_spec = BuiltinParameterSpecNoKeywords("bin", ("number",), default_count=0)
builtin_oct_spec = BuiltinParameterSpecNoKeywords("oct", ("number",), default_count=0)
builtin_hex_spec = BuiltinParameterSpecNoKeywords("hex", ("number",), default_count=0)
builtin_id_spec = BuiltinParameterSpecNoKeywords("id", ("object",), default_count=0)
builtin_repr_spec = BuiltinParameterSpecNoKeywords("repr", ("object",), default_count=0)
builtin_dir_spec = BuiltinParameterSpecNoKeywords("dir", ("object",), default_count=1)
builtin_vars_spec = BuiltinParameterSpecNoKeywords("vars", ("object",), default_count=1)
builtin_locals_spec = BuiltinParameterSpecNoKeywords("locals", (), default_count=0)
builtin_globals_spec = BuiltinParameterSpecNoKeywords("globals", (), default_count=0)
builtin_eval_spec = BuiltinParameterSpecNoKeywords(
"eval", ("source", "globals", "locals"), 2
)
if python_version < 0x300:
builtin_compile_spec = BuiltinParameterSpec(
"compile",
("source", "filename", "mode", "flags", "dont_inherit"),
default_count=2,
)
else:
builtin_compile_spec = BuiltinParameterSpec(
"compile",
("source", "filename", "mode", "flags", "dont_inherit", "optimize"),
default_count=3,
)
if python_version >= 0x300:
builtin_exec_spec = BuiltinParameterSpecNoKeywords(
"exec", ("source", "globals", "locals"), default_count=2
)
# Note: Iter in fact names its first argument if the default applies
# "collection", fixed up in a wrapper.
builtin_iter_spec = BuiltinParameterSpecNoKeywords(
"iter", ("callable", "sentinel"), default_count=1
)
builtin_next_spec = BuiltinParameterSpecNoKeywords(
"next", ("iterator", "default"), default_count=1
)
# Note: type with 1 and type with 3 arguments are too different.
builtin_type1_spec = BuiltinParameterSpecNoKeywords(
"type", ("object",), default_count=0
)
builtin_type3_spec = BuiltinParameterSpecNoKeywords(
"type", ("name", "bases", "dict"), default_count=0
)
builtin_super_spec = BuiltinParameterSpecNoKeywords(
"super", ("type", "object"), default_count=1 if python_version < 0x300 else 2
)
builtin_hasattr_spec = BuiltinParameterSpecNoKeywords(
"hasattr", ("object", "name"), default_count=0
)
builtin_getattr_spec = BuiltinParameterSpecNoKeywords(
"getattr", ("object", "name", "default"), default_count=1
)
builtin_setattr_spec = BuiltinParameterSpecNoKeywords(
"setattr", ("object", "name", "value"), default_count=0
)
builtin_isinstance_spec = BuiltinParameterSpecNoKeywords(
"isinstance", ("instance", "classes"), default_count=0
)
builtin_issubclass_spec = BuiltinParameterSpecNoKeywords(
"issubclass", ("cls", "classes"), default_count=0
)
class BuiltinBytearraySpec(BuiltinParameterSpecPosArgs):
def isCompileTimeComputable(self, values):
# For bytearrays, we need to avoid the case of large bytearray
# construction from an integer at compile time.
result = BuiltinParameterSpec.isCompileTimeComputable(self, values=values)
if result and len(values) == 1:
index_value = values[0].getIndexValue()
if index_value is None:
return result
return index_value < 256
else:
return result
builtin_bytearray_spec = BuiltinBytearraySpec(
"bytearray", ("string",), ("encoding", "errors"), default_count=2
)
builtin_bytes_p3_spec = BuiltinBytearraySpec(
"bytes", ("string",), ("encoding", "errors"), default_count=3
)
# Beware: One argument version defines "stop", not "start".
builtin_slice_spec = BuiltinParameterSpecNoKeywords(
"slice", ("start", "stop", "step"), default_count=2
)
builtin_hash_spec = BuiltinParameterSpecNoKeywords("hash", ("object",), default_count=0)
builtin_format_spec = BuiltinParameterSpecNoKeywords(
"format", ("value", "format_spec"), default_count=1
)
if python_version < 0x380:
builtin_sum_spec = BuiltinParameterSpecNoKeywords(
"sum", ("sequence", "start"), default_count=1
)
else:
builtin_sum_spec = BuiltinParameterSpecPosArgs(
"sum", ("sequence",), ("start",), default_count=1
)
builtin_staticmethod_spec = BuiltinParameterSpecNoKeywords(
"staticmethod", ("function",), default_count=0
)
builtin_classmethod_spec = BuiltinParameterSpecNoKeywords(
"classmethod", ("function",), default_count=0
)
if python_version < 0x300:
builtin_sorted_spec = BuiltinParameterSpecNoKeywords(
"sorted", ("iterable", "cmp", "key", "reverse"), default_count=2
)
else:
builtin_sorted_spec = BuiltinParameterSpecNoKeywords(
"sorted", ("iterable", "key", "reverse"), default_count=2
)
builtin_reversed_spec = BuiltinParameterSpecNoKeywords(
"reversed", ("object",), default_count=0
)
builtin_reversed_spec = BuiltinParameterSpecNoKeywords(
"reversed", ("object",), default_count=0
)
if python_version < 0x300:
builtin_enumerate_spec = BuiltinParameterSpec(
"enumerate", ("sequence", "start"), default_count=1
)
else:
builtin_enumerate_spec = BuiltinParameterSpec(
"enumerate", ("iterable", "start"), default_count=1
)
class BuiltinRangeSpec(BuiltinParameterSpecNoKeywords):
def isCompileTimeComputable(self, values):
# For ranges, we need have many cases that can prevent the ability
# to pre-compute, pylint: disable=too-many-branches,too-many-return-statements
result = BuiltinParameterSpecNoKeywords.isCompileTimeComputable(
self, values=values
)
if result:
arg_count = len(values)
if arg_count == 1:
low = values[0]
# If it's not a number constant, we can compute the exception
if not low.isNumberConstant():
return True
return low.getCompileTimeConstant() < 256
elif arg_count == 2:
low, high = values
# that will be raised.
if not low.isNumberConstant() or not high.isNumberConstant():
return True
return (
high.getCompileTimeConstant() - low.getCompileTimeConstant() < 256
)
elif arg_count == 3:
low, high, step = values
if (
not low.isNumberConstant()
or not high.isNumberConstant()
or not step.isNumberConstant()
):
return True
low = low.getCompileTimeConstant()
high = high.getCompileTimeConstant()
step = step.getCompileTimeConstant()
# It's going to give a ZeroDivisionError in this case.
if step == 0:
return True
if low < high:
if step < 0:
return True
else:
return math.ceil(float(high - low) / step) < 256
else:
if step > 0:
return True
else:
return math.ceil(float(high - low) / step) < 256
else:
assert False
else:
return False
builtin_range_spec = BuiltinRangeSpec(
"range", ("start", "stop", "step"), default_count=2
)
if python_version >= 0x300:
builtin_ascii_spec = BuiltinParameterSpecNoKeywords(
"ascii", ("object",), default_count=0
)
builtin_divmod_spec = BuiltinParameterSpecNoKeywords(
"divmod", ("left", "right"), default_count=0
)
def extractBuiltinArgs(node, builtin_spec, builtin_class, empty_special_class=None):
try:
kw = node.subnode_kwargs
if kw is not None:
if not kw.isMappingWithConstantStringKeys():
return None
pairs = kw.getMappingStringKeyPairs()
if pairs and not builtin_spec.allowsKeywords():
raise TooManyArguments(TypeError(builtin_spec.getKeywordRefusalText()))
else:
pairs = ()
args = node.subnode_args
if args:
if not args.canPredictIterationValues():
return None
positional = args.getIterationValues()
else:
positional = ()
if not positional and not pairs and empty_special_class is not None:
return empty_special_class(source_ref=node.getSourceReference())
args_dict = matchCall(
func_name=builtin_spec.getName(),
args=builtin_spec.getArgumentNames(),
kw_only_args=builtin_spec.getKwOnlyParameterNames(),
star_list_arg=builtin_spec.getStarListArgumentName(),
star_dict_arg=builtin_spec.getStarDictArgumentName(),
num_defaults=builtin_spec.getDefaultCount(),
num_posonly=builtin_spec.getPosOnlyParameterCount(),
positional=positional,
pairs=pairs,
)
except TooManyArguments as e:
from nuitka.nodes.NodeMakingHelpers import (
makeRaiseExceptionReplacementExpressionFromInstance,
wrapExpressionWithSideEffects,
)
return wrapExpressionWithSideEffects(
new_node=makeRaiseExceptionReplacementExpressionFromInstance(
expression=node, exception=e.getRealException()
),
old_node=node,
side_effects=node.extractSideEffectsPreCall(),
)
args_list = []
for argument_name in builtin_spec.getArgumentNames():
args_list.append(args_dict[argument_name])
if builtin_spec.getStarListArgumentName() is not None:
args_list.append(args_dict[builtin_spec.getStarListArgumentName()])
if builtin_spec.getStarDictArgumentName() is not None:
args_list.append(args_dict[builtin_spec.getStarDictArgumentName()])
for argument_name in builtin_spec.getKwOnlyParameterNames():
args_list.append(args_dict[argument_name])
result = builtin_class(*args_list, source_ref=node.getSourceReference())
if python_version < 0x380:
result.setCompatibleSourceReference(node.getCompatibleSourceReference())
return result
| true | true |
f72c344f2c08cfd3448f089e38a1116d9b085c4c | 17,366 | py | Python | docker-images/taigav2/taiga-back/settings/common.py | mattcongy/itshop | 6be025a9eaa7fe7f495b5777d1f0e5a3184121c9 | [
"MIT"
] | 1 | 2017-05-29T19:01:06.000Z | 2017-05-29T19:01:06.000Z | docker-images/taigav2/taiga-back/settings/common.py | mattcongy/itshop | 6be025a9eaa7fe7f495b5777d1f0e5a3184121c9 | [
"MIT"
] | null | null | null | docker-images/taigav2/taiga-back/settings/common.py | mattcongy/itshop | 6be025a9eaa7fe7f495b5777d1f0e5a3184121c9 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os.path, sys, os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
APPEND_SLASH = False
ALLOWED_HOSTS = ["*"]
ADMINS = (
("Admin", "example@example.com"),
)
DEBUG = False
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "taiga",
}
}
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "unique-snowflake"
}
}
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
]
# Default configuration for reverse proxy
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https")
# Errors report configuration
SEND_BROKEN_LINK_EMAILS = True
IGNORABLE_404_ENDS = (".php", ".cgi")
IGNORABLE_404_STARTS = ("/phpmyadmin/",)
ATOMIC_REQUESTS = True
TIME_ZONE = "UTC"
LOGIN_URL="/auth/login/"
USE_TZ = True
USE_I18N = True
USE_L10N = True
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
# Languages we provide translations for, out of the box.
LANGUAGES = [
#("af", "Afrikaans"), # Afrikaans
#("ar", "العربية"), # Arabic
#("ast", "Asturiano"), # Asturian
#("az", "Azərbaycan dili"), # Azerbaijani
#("bg", "Български"), # Bulgarian
#("be", "Беларуская"), # Belarusian
#("bn", "বাংলা"), # Bengali
#("br", "Bretón"), # Breton
#("bs", "Bosanski"), # Bosnian
("ca", "Català"), # Catalan
#("cs", "Čeština"), # Czech
#("cy", "Cymraeg"), # Welsh
#("da", "Dansk"), # Danish
("de", "Deutsch"), # German
#("el", "Ελληνικά"), # Greek
("en", "English (US)"), # English
#("en-au", "English (Australia)"), # Australian English
#("en-gb", "English (UK)"), # British English
#("eo", "esperanta"), # Esperanto
("es", "Español"), # Spanish
#("es-ar", "Español (Argentina)"), # Argentinian Spanish
#("es-mx", "Español (México)"), # Mexican Spanish
#("es-ni", "Español (Nicaragua)"), # Nicaraguan Spanish
#("es-ve", "Español (Venezuela)"), # Venezuelan Spanish
#("et", "Eesti"), # Estonian
#("eu", "Euskara"), # Basque
#("fa", "فارسی"), # Persian
("fi", "Suomi"), # Finnish
("fr", "Français"), # French
#("fy", "Frysk"), # Frisian
#("ga", "Irish"), # Irish
#("gl", "Galego"), # Galician
#("he", "עברית"), # Hebrew
#("hi", "हिन्दी"), # Hindi
#("hr", "Hrvatski"), # Croatian
#("hu", "Magyar"), # Hungarian
#("ia", "Interlingua"), # Interlingua
#("id", "Bahasa Indonesia"), # Indonesian
#("io", "IDO"), # Ido
#("is", "Íslenska"), # Icelandic
("it", "Italiano"), # Italian
#("ja", "日本語"), # Japanese
#("ka", "ქართული"), # Georgian
#("kk", "Қазақша"), # Kazakh
#("km", "ភាសាខ្មែរ"), # Khmer
#("kn", "ಕನ್ನಡ"), # Kannada
#("ko", "한국어"), # Korean
#("lb", "Lëtzebuergesch"), # Luxembourgish
#("lt", "Lietuvių"), # Lithuanian
#("lv", "Latviešu"), # Latvian
#("mk", "Македонски"), # Macedonian
#("ml", "മലയാളം"), # Malayalam
#("mn", "Монгол"), # Mongolian
#("mr", "मराठी"), # Marathi
#("my", "မြန်မာ"), # Burmese
("nb", "Norsk (bokmål)"), # Norwegian Bokmal
#("ne", "नेपाली"), # Nepali
("nl", "Nederlands"), # Dutch
#("nn", "Norsk (nynorsk)"), # Norwegian Nynorsk
#("os", "Ирон æвзаг"), # Ossetic
#("pa", "ਪੰਜਾਬੀ"), # Punjabi
("pl", "Polski"), # Polish
#("pt", "Português (Portugal)"), # Portuguese
("pt-br", "Português (Brasil)"), # Brazilian Portuguese
#("ro", "Română"), # Romanian
("ru", "Русский"), # Russian
#("sk", "Slovenčina"), # Slovak
#("sl", "Slovenščina"), # Slovenian
#("sq", "Shqip"), # Albanian
#("sr", "Српски"), # Serbian
#("sr-latn", "srpski"), # Serbian Latin
("sv", "Svenska"), # Swedish
#("sw", "Kiswahili"), # Swahili
#("ta", "தமிழ்"), # Tamil
#("te", "తెలుగు"), # Telugu
#("th", "ภาษาไทย"), # Thai
("tr", "Türkçe"), # Turkish
#("tt", "татар теле"), # Tatar
#("udm", "удмурт кыл"), # Udmurt
#("uk", "Українська"), # Ukrainian
#("ur", "اردو"), # Urdu
#("vi", "Tiếng Việt"), # Vietnamese
#("zh-hans", "中文(简体)"), # Simplified Chinese
("zh-hant", "中文(香港)"), # Traditional Chinese
]
# Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI = ["he", "ar", "fa", "ur"]
LOCALE_PATHS = (
os.path.join(BASE_DIR, "locale"),
os.path.join(BASE_DIR, "taiga", "locale"),
)
SITES = {
"api": {"domain": "localhost:8000", "scheme": "http", "name": "api"},
"front": {"domain": "localhost:9001", "scheme": "http", "name": "front"},
}
SITE_ID = "api"
# Session configuration (only used for admin)
SESSION_ENGINE = "django.contrib.sessions.backends.db"
SESSION_COOKIE_AGE = 1209600 # (2 weeks)
# MAIL OPTIONS
DEFAULT_FROM_EMAIL = "john@doe.com"
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DJMAIL_REAL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DJMAIL_SEND_ASYNC = True
DJMAIL_MAX_RETRY_NUMBER = 3
DJMAIL_TEMPLATE_EXTENSION = "jinja"
# Events backend
EVENTS_PUSH_BACKEND = "taiga.events.backends.postgresql.EventsPushBackend"
# EVENTS_PUSH_BACKEND = "taiga.events.backends.rabbitmq.EventsPushBackend"
# EVENTS_PUSH_BACKEND_OPTIONS = {"url": "//guest:guest@127.0.0.1/"}
# Message System
MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
# The absolute url is mandatory because attachments
# urls depends on it. On production should be set
# something like https://media.taiga.io/
MEDIA_URL = "http://localhost:8000/media/"
STATIC_URL = "http://localhost:8000/static/"
# Static configuration.
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Don't forget to use absolute paths, not relative paths.
)
# Defautl storage
DEFAULT_FILE_STORAGE = "taiga.base.storage.FileSystemStorage"
SECRET_KEY = "aw3+t2r(8(0kkrhg8)gx6i96v5^kv%6cfep9wxfom0%7dy0m9e"
TEMPLATES = [
{
"BACKEND": "django_jinja.backend.Jinja2",
"DIRS": [
os.path.join(BASE_DIR, "templates"),
],
"APP_DIRS": True,
"OPTIONS": {
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.request",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
"match_extension": ".jinja",
}
},
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
os.path.join(BASE_DIR, "templates"),
],
"APP_DIRS": True,
"OPTIONS": {
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.request",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
}
},
]
MIDDLEWARE_CLASSES = [
"taiga.base.middleware.cors.CoorsMiddleware",
"taiga.events.middleware.SessionIDMiddleware",
# Common middlewares
"django.middleware.common.CommonMiddleware",
"django.middleware.locale.LocaleMiddleware",
# Only needed by django admin
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
ROOT_URLCONF = "taiga.urls"
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.admin",
"django.contrib.staticfiles",
"django.contrib.sitemaps",
"taiga.base",
"taiga.base.api",
"taiga.locale",
"taiga.events",
"taiga.front",
"taiga.users",
"taiga.userstorage",
"taiga.external_apps",
"taiga.projects",
"taiga.projects.references",
"taiga.projects.custom_attributes",
"taiga.projects.history",
"taiga.projects.notifications",
"taiga.projects.attachments",
"taiga.projects.likes",
"taiga.projects.votes",
"taiga.projects.milestones",
"taiga.projects.epics",
"taiga.projects.userstories",
"taiga.projects.tasks",
"taiga.projects.issues",
"taiga.projects.wiki",
"taiga.searches",
"taiga.timeline",
"taiga.mdrender",
"taiga.export_import",
"taiga.feedback",
"taiga.stats",
"taiga.hooks.github",
"taiga.hooks.gitlab",
"taiga.hooks.bitbucket",
"taiga.hooks.gogs",
"taiga.webhooks",
"djmail",
"django_jinja",
"django_jinja.contrib._humanize",
"sr",
"easy_thumbnails",
"raven.contrib.django.raven_compat",
]
WSGI_APPLICATION = "taiga.wsgi.application"
LOGGING = {
"version": 1,
"disable_existing_loggers": True,
"filters": {
"require_debug_false": {
"()": "django.utils.log.RequireDebugFalse"
}
},
"formatters": {
"complete": {
"format": "%(levelname)s:%(asctime)s:%(module)s %(message)s"
},
"simple": {
"format": "%(levelname)s:%(asctime)s: %(message)s"
},
"null": {
"format": "%(message)s",
},
},
"handlers": {
"null": {
"level":"DEBUG",
"class":"logging.NullHandler",
},
"console":{
"level":"DEBUG",
"class":"logging.StreamHandler",
"formatter": "simple",
},
"mail_admins": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler",
}
},
"loggers": {
"django": {
"handlers":["null"],
"propagate": True,
"level":"INFO",
},
"django.request": {
"handlers": ["mail_admins", "console"],
"level": "ERROR",
"propagate": False,
},
"taiga.export_import": {
"handlers": ["mail_admins", "console"],
"level": "ERROR",
"propagate": False,
},
"taiga": {
"handlers": ["console"],
"level": "DEBUG",
"propagate": False,
}
}
}
AUTH_USER_MODEL = "users.User"
FORMAT_MODULE_PATH = "taiga.base.formats"
DATE_INPUT_FORMATS = (
"%Y-%m-%d", "%m/%d/%Y", "%d/%m/%Y", "%b %d %Y",
"%b %d, %Y", "%d %b %Y", "%d %b, %Y", "%B %d %Y",
"%B %d, %Y", "%d %B %Y", "%d %B, %Y"
)
# Authentication settings (only for django admin)
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend", # default
)
MAX_AGE_AUTH_TOKEN = None
MAX_AGE_CANCEL_ACCOUNT = 30 * 24 * 60 * 60 # 30 days in seconds
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
# Mainly used by taiga-front
"taiga.auth.backends.Token",
# Mainly used for api debug.
"taiga.auth.backends.Session",
# Application tokens auth
"taiga.external_apps.auth_backends.Token",
),
"DEFAULT_THROTTLE_CLASSES": (
"taiga.base.throttling.AnonRateThrottle",
"taiga.base.throttling.UserRateThrottle"
),
"DEFAULT_THROTTLE_RATES": {
"anon": None,
"user": None,
"import-mode": None,
"import-dump-mode": "1/minute",
"create-memberships": None
},
"FILTER_BACKEND": "taiga.base.filters.FilterBackend",
"EXCEPTION_HANDLER": "taiga.base.exceptions.exception_handler",
"PAGINATE_BY": 30,
"PAGINATE_BY_PARAM": "page_size",
"MAX_PAGINATE_BY": 1000,
"DATETIME_FORMAT": "%Y-%m-%dT%H:%M:%S%z"
}
# Extra expose header related to Taiga APP (see taiga.base.middleware.cors=)
APP_EXTRA_EXPOSE_HEADERS = [
"taiga-info-total-opened-milestones",
"taiga-info-total-closed-milestones",
"taiga-info-project-memberships",
"taiga-info-project-is-private",
"taiga-info-order-updated"
]
DEFAULT_PROJECT_TEMPLATE = "scrum"
PUBLIC_REGISTER_ENABLED = False
# None or [] values in USER_EMAIL_ALLOWED_DOMAINS means allow any domain
USER_EMAIL_ALLOWED_DOMAINS = None
SEARCHES_MAX_RESULTS = 150
SOUTH_MIGRATION_MODULES = {
'easy_thumbnails': 'easy_thumbnails.south_migrations',
}
THN_AVATAR_SIZE = 80 # 80x80 pixels
THN_AVATAR_BIG_SIZE = 300 # 300x300 pixels
THN_LOGO_SMALL_SIZE = 80 # 80x80 pixels
THN_LOGO_BIG_SIZE = 300 # 300x300 pixels
THN_TIMELINE_IMAGE_SIZE = 640 # 640x??? pixels
THN_CARD_IMAGE_WIDTH = 300 # 300 pixels
THN_CARD_IMAGE_HEIGHT = 200 # 200 pixels
THN_AVATAR_SMALL = "avatar"
THN_AVATAR_BIG = "big-avatar"
THN_LOGO_SMALL = "logo-small"
THN_LOGO_BIG = "logo-big"
THN_ATTACHMENT_TIMELINE = "timeline-image"
THN_ATTACHMENT_CARD = "card-image"
THUMBNAIL_ALIASES = {
"": {
THN_AVATAR_SMALL: {"size": (THN_AVATAR_SIZE, THN_AVATAR_SIZE), "crop": True},
THN_AVATAR_BIG: {"size": (THN_AVATAR_BIG_SIZE, THN_AVATAR_BIG_SIZE), "crop": True},
THN_LOGO_SMALL: {"size": (THN_LOGO_SMALL_SIZE, THN_LOGO_SMALL_SIZE), "crop": True},
THN_LOGO_BIG: {"size": (THN_LOGO_BIG_SIZE, THN_LOGO_BIG_SIZE), "crop": True},
THN_ATTACHMENT_TIMELINE: {"size": (THN_TIMELINE_IMAGE_SIZE, 0), "crop": True},
THN_ATTACHMENT_CARD: {"size": (THN_CARD_IMAGE_WIDTH, THN_CARD_IMAGE_HEIGHT), "crop": True},
},
}
TAGS_PREDEFINED_COLORS = ["#fce94f", "#edd400", "#c4a000", "#8ae234",
"#73d216", "#4e9a06", "#d3d7cf", "#fcaf3e",
"#f57900", "#ce5c00", "#729fcf", "#3465a4",
"#204a87", "#888a85", "#ad7fa8", "#75507b",
"#5c3566", "#ef2929", "#cc0000", "#a40000",
"#2e3436",]
# Feedback module settings
FEEDBACK_ENABLED = True
FEEDBACK_EMAIL = "support@taiga.io"
# Stats module settings
STATS_ENABLED = False
STATS_CACHE_TIMEOUT = 60*60 # In second
# 0 notifications will work in a synchronous way
# >0 an external process will check the pending notifications and will send them
# collapsed during that interval
CHANGE_NOTIFICATIONS_MIN_INTERVAL = 0 #seconds
# List of functions called for filling correctly the ProjectModulesConfig associated to a project
# This functions should receive a Project parameter and return a dict with the desired configuration
PROJECT_MODULES_CONFIGURATORS = {
"github": "taiga.hooks.github.services.get_or_generate_config",
"gitlab": "taiga.hooks.gitlab.services.get_or_generate_config",
"bitbucket": "taiga.hooks.bitbucket.services.get_or_generate_config",
"gogs": "taiga.hooks.gogs.services.get_or_generate_config",
}
BITBUCKET_VALID_ORIGIN_IPS = ["131.103.20.165", "131.103.20.166", "104.192.143.192/28", "104.192.143.208/28"]
GITLAB_VALID_ORIGIN_IPS = []
EXPORTS_TTL = 60 * 60 * 24 # 24 hours
CELERY_ENABLED = False
WEBHOOKS_ENABLED = False
# If is True /front/sitemap.xml show a valid sitemap of taiga-front client
FRONT_SITEMAP_ENABLED = False
FRONT_SITEMAP_CACHE_TIMEOUT = 24*60*60 # In second
EXTRA_BLOCKING_CODES = []
MAX_PRIVATE_PROJECTS_PER_USER = None # None == no limit
MAX_PUBLIC_PROJECTS_PER_USER = None # None == no limit
MAX_MEMBERSHIPS_PRIVATE_PROJECTS = None # None == no limit
MAX_MEMBERSHIPS_PUBLIC_PROJECTS = None # None == no limit
MAX_PENDING_MEMBERSHIPS = 30 # Max number of unconfirmed memberships in a project
from .sr import *
# NOTE: DON'T INSERT MORE SETTINGS AFTER THIS LINE
TEST_RUNNER="django.test.runner.DiscoverRunner"
if "test" in sys.argv:
print ("\033[1;91mNo django tests.\033[0m")
print ("Try: \033[1;33mpy.test\033[0m")
sys.exit(0)
| 31.632058 | 109 | 0.620293 |
import os.path, sys, os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
APPEND_SLASH = False
ALLOWED_HOSTS = ["*"]
ADMINS = (
("Admin", "example@example.com"),
)
DEBUG = False
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "taiga",
}
}
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "unique-snowflake"
}
}
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
]
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https")
SEND_BROKEN_LINK_EMAILS = True
IGNORABLE_404_ENDS = (".php", ".cgi")
IGNORABLE_404_STARTS = ("/phpmyadmin/",)
ATOMIC_REQUESTS = True
TIME_ZONE = "UTC"
LOGIN_URL="/auth/login/"
USE_TZ = True
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = 'en-us'
LANGUAGES = [
"English (US)"),
AGES_BIDI = ["he", "ar", "fa", "ur"]
LOCALE_PATHS = (
os.path.join(BASE_DIR, "locale"),
os.path.join(BASE_DIR, "taiga", "locale"),
)
SITES = {
"api": {"domain": "localhost:8000", "scheme": "http", "name": "api"},
"front": {"domain": "localhost:9001", "scheme": "http", "name": "front"},
}
SITE_ID = "api"
SESSION_ENGINE = "django.contrib.sessions.backends.db"
SESSION_COOKIE_AGE = 1209600
DEFAULT_FROM_EMAIL = "john@doe.com"
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DJMAIL_REAL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DJMAIL_SEND_ASYNC = True
DJMAIL_MAX_RETRY_NUMBER = 3
DJMAIL_TEMPLATE_EXTENSION = "jinja"
EVENTS_PUSH_BACKEND = "taiga.events.backends.postgresql.EventsPushBackend"
MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
MEDIA_URL = "http://localhost:8000/media/"
STATIC_URL = "http://localhost:8000/static/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
STATICFILES_DIRS = (
)
# Defautl storage
DEFAULT_FILE_STORAGE = "taiga.base.storage.FileSystemStorage"
SECRET_KEY = "aw3+t2r(8(0kkrhg8)gx6i96v5^kv%6cfep9wxfom0%7dy0m9e"
TEMPLATES = [
{
"BACKEND": "django_jinja.backend.Jinja2",
"DIRS": [
os.path.join(BASE_DIR, "templates"),
],
"APP_DIRS": True,
"OPTIONS": {
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.request",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
"match_extension": ".jinja",
}
},
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
os.path.join(BASE_DIR, "templates"),
],
"APP_DIRS": True,
"OPTIONS": {
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.request",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
}
},
]
MIDDLEWARE_CLASSES = [
"taiga.base.middleware.cors.CoorsMiddleware",
"taiga.events.middleware.SessionIDMiddleware",
# Common middlewares
"django.middleware.common.CommonMiddleware",
"django.middleware.locale.LocaleMiddleware",
# Only needed by django admin
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
ROOT_URLCONF = "taiga.urls"
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.admin",
"django.contrib.staticfiles",
"django.contrib.sitemaps",
"taiga.base",
"taiga.base.api",
"taiga.locale",
"taiga.events",
"taiga.front",
"taiga.users",
"taiga.userstorage",
"taiga.external_apps",
"taiga.projects",
"taiga.projects.references",
"taiga.projects.custom_attributes",
"taiga.projects.history",
"taiga.projects.notifications",
"taiga.projects.attachments",
"taiga.projects.likes",
"taiga.projects.votes",
"taiga.projects.milestones",
"taiga.projects.epics",
"taiga.projects.userstories",
"taiga.projects.tasks",
"taiga.projects.issues",
"taiga.projects.wiki",
"taiga.searches",
"taiga.timeline",
"taiga.mdrender",
"taiga.export_import",
"taiga.feedback",
"taiga.stats",
"taiga.hooks.github",
"taiga.hooks.gitlab",
"taiga.hooks.bitbucket",
"taiga.hooks.gogs",
"taiga.webhooks",
"djmail",
"django_jinja",
"django_jinja.contrib._humanize",
"sr",
"easy_thumbnails",
"raven.contrib.django.raven_compat",
]
WSGI_APPLICATION = "taiga.wsgi.application"
LOGGING = {
"version": 1,
"disable_existing_loggers": True,
"filters": {
"require_debug_false": {
"()": "django.utils.log.RequireDebugFalse"
}
},
"formatters": {
"complete": {
"format": "%(levelname)s:%(asctime)s:%(module)s %(message)s"
},
"simple": {
"format": "%(levelname)s:%(asctime)s: %(message)s"
},
"null": {
"format": "%(message)s",
},
},
"handlers": {
"null": {
"level":"DEBUG",
"class":"logging.NullHandler",
},
"console":{
"level":"DEBUG",
"class":"logging.StreamHandler",
"formatter": "simple",
},
"mail_admins": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler",
}
},
"loggers": {
"django": {
"handlers":["null"],
"propagate": True,
"level":"INFO",
},
"django.request": {
"handlers": ["mail_admins", "console"],
"level": "ERROR",
"propagate": False,
},
"taiga.export_import": {
"handlers": ["mail_admins", "console"],
"level": "ERROR",
"propagate": False,
},
"taiga": {
"handlers": ["console"],
"level": "DEBUG",
"propagate": False,
}
}
}
AUTH_USER_MODEL = "users.User"
FORMAT_MODULE_PATH = "taiga.base.formats"
DATE_INPUT_FORMATS = (
"%Y-%m-%d", "%m/%d/%Y", "%d/%m/%Y", "%b %d %Y",
"%b %d, %Y", "%d %b %Y", "%d %b, %Y", "%B %d %Y",
"%B %d, %Y", "%d %B %Y", "%d %B, %Y"
)
# Authentication settings (only for django admin)
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend", # default
)
MAX_AGE_AUTH_TOKEN = None
MAX_AGE_CANCEL_ACCOUNT = 30 * 24 * 60 * 60 # 30 days in seconds
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
# Mainly used by taiga-front
"taiga.auth.backends.Token",
# Mainly used for api debug.
"taiga.auth.backends.Session",
# Application tokens auth
"taiga.external_apps.auth_backends.Token",
),
"DEFAULT_THROTTLE_CLASSES": (
"taiga.base.throttling.AnonRateThrottle",
"taiga.base.throttling.UserRateThrottle"
),
"DEFAULT_THROTTLE_RATES": {
"anon": None,
"user": None,
"import-mode": None,
"import-dump-mode": "1/minute",
"create-memberships": None
},
"FILTER_BACKEND": "taiga.base.filters.FilterBackend",
"EXCEPTION_HANDLER": "taiga.base.exceptions.exception_handler",
"PAGINATE_BY": 30,
"PAGINATE_BY_PARAM": "page_size",
"MAX_PAGINATE_BY": 1000,
"DATETIME_FORMAT": "%Y-%m-%dT%H:%M:%S%z"
}
# Extra expose header related to Taiga APP (see taiga.base.middleware.cors=)
APP_EXTRA_EXPOSE_HEADERS = [
"taiga-info-total-opened-milestones",
"taiga-info-total-closed-milestones",
"taiga-info-project-memberships",
"taiga-info-project-is-private",
"taiga-info-order-updated"
]
DEFAULT_PROJECT_TEMPLATE = "scrum"
PUBLIC_REGISTER_ENABLED = False
# None or [] values in USER_EMAIL_ALLOWED_DOMAINS means allow any domain
USER_EMAIL_ALLOWED_DOMAINS = None
SEARCHES_MAX_RESULTS = 150
SOUTH_MIGRATION_MODULES = {
'easy_thumbnails': 'easy_thumbnails.south_migrations',
}
THN_AVATAR_SIZE = 80 # 80x80 pixels
THN_AVATAR_BIG_SIZE = 300 # 300x300 pixels
THN_LOGO_SMALL_SIZE = 80 # 80x80 pixels
THN_LOGO_BIG_SIZE = 300 # 300x300 pixels
THN_TIMELINE_IMAGE_SIZE = 640 # 640x??? pixels
THN_CARD_IMAGE_WIDTH = 300 # 300 pixels
THN_CARD_IMAGE_HEIGHT = 200 # 200 pixels
THN_AVATAR_SMALL = "avatar"
THN_AVATAR_BIG = "big-avatar"
THN_LOGO_SMALL = "logo-small"
THN_LOGO_BIG = "logo-big"
THN_ATTACHMENT_TIMELINE = "timeline-image"
THN_ATTACHMENT_CARD = "card-image"
THUMBNAIL_ALIASES = {
"": {
THN_AVATAR_SMALL: {"size": (THN_AVATAR_SIZE, THN_AVATAR_SIZE), "crop": True},
THN_AVATAR_BIG: {"size": (THN_AVATAR_BIG_SIZE, THN_AVATAR_BIG_SIZE), "crop": True},
THN_LOGO_SMALL: {"size": (THN_LOGO_SMALL_SIZE, THN_LOGO_SMALL_SIZE), "crop": True},
THN_LOGO_BIG: {"size": (THN_LOGO_BIG_SIZE, THN_LOGO_BIG_SIZE), "crop": True},
THN_ATTACHMENT_TIMELINE: {"size": (THN_TIMELINE_IMAGE_SIZE, 0), "crop": True},
THN_ATTACHMENT_CARD: {"size": (THN_CARD_IMAGE_WIDTH, THN_CARD_IMAGE_HEIGHT), "crop": True},
},
}
TAGS_PREDEFINED_COLORS = ["#fce94f", "#edd400", "#c4a000", "#8ae234",
"#73d216", "#4e9a06", "#d3d7cf", "#fcaf3e",
"#f57900", "#ce5c00", "#729fcf", "#3465a4",
"#204a87", "#888a85", "#ad7fa8", "#75507b",
"#5c3566", "#ef2929", "#cc0000", "#a40000",
"#2e3436",]
# Feedback module settings
FEEDBACK_ENABLED = True
FEEDBACK_EMAIL = "support@taiga.io"
# Stats module settings
STATS_ENABLED = False
STATS_CACHE_TIMEOUT = 60*60 # In second
# 0 notifications will work in a synchronous way
# >0 an external process will check the pending notifications and will send them
# collapsed during that interval
CHANGE_NOTIFICATIONS_MIN_INTERVAL = 0 #seconds
# List of functions called for filling correctly the ProjectModulesConfig associated to a project
# This functions should receive a Project parameter and return a dict with the desired configuration
PROJECT_MODULES_CONFIGURATORS = {
"github": "taiga.hooks.github.services.get_or_generate_config",
"gitlab": "taiga.hooks.gitlab.services.get_or_generate_config",
"bitbucket": "taiga.hooks.bitbucket.services.get_or_generate_config",
"gogs": "taiga.hooks.gogs.services.get_or_generate_config",
}
BITBUCKET_VALID_ORIGIN_IPS = ["131.103.20.165", "131.103.20.166", "104.192.143.192/28", "104.192.143.208/28"]
GITLAB_VALID_ORIGIN_IPS = []
EXPORTS_TTL = 60 * 60 * 24 # 24 hours
CELERY_ENABLED = False
WEBHOOKS_ENABLED = False
# If is True /front/sitemap.xml show a valid sitemap of taiga-front client
FRONT_SITEMAP_ENABLED = False
FRONT_SITEMAP_CACHE_TIMEOUT = 24*60*60 # In second
EXTRA_BLOCKING_CODES = []
MAX_PRIVATE_PROJECTS_PER_USER = None # None == no limit
MAX_PUBLIC_PROJECTS_PER_USER = None # None == no limit
MAX_MEMBERSHIPS_PRIVATE_PROJECTS = None # None == no limit
MAX_MEMBERSHIPS_PUBLIC_PROJECTS = None # None == no limit
MAX_PENDING_MEMBERSHIPS = 30 # Max number of unconfirmed memberships in a project
from .sr import *
# NOTE: DON'T INSERT MORE SETTINGS AFTER THIS LINE
TEST_RUNNER="django.test.runner.DiscoverRunner"
if "test" in sys.argv:
print ("\033[1;91mNo django tests.\033[0m")
print ("Try: \033[1;33mpy.test\033[0m")
sys.exit(0)
| true | true |
f72c3524f818483a439794d6f178598c2f531f0c | 773 | py | Python | models/product.py | KennyLingineni/MiniAmazon | 95c72d3693466ca2265d0e13f2cb172e1a98c260 | [
"Unlicense"
] | null | null | null | models/product.py | KennyLingineni/MiniAmazon | 95c72d3693466ca2265d0e13f2cb172e1a98c260 | [
"Unlicense"
] | null | null | null | models/product.py | KennyLingineni/MiniAmazon | 95c72d3693466ca2265d0e13f2cb172e1a98c260 | [
"Unlicense"
] | null | null | null | from MiniAmazon.models import db
def search_by_name(query):
#Search for the product here
db_query = {'name': query}
matchingproducts = db['products'].find(db_query) # Products is the table/collection. It returns a cursor(pointer).Cursor is a type of Generator.
if matchingproducts:
return list(matchingproducts) # make sure you convert the cursor to list before you send
else:
return []
def add_product(producttobeadded):
#Add the Product Here
db['products'].insert_one(producttobeadded)
def update_product(productnametobeupdated, updated_product):
filter={'name': productnametobeupdated}
update = {
'$set': updated_product
}
# update in DB
db['products'].update_one(filter=filter, update=update) | 33.608696 | 149 | 0.711514 | from MiniAmazon.models import db
def search_by_name(query):
db_query = {'name': query}
matchingproducts = db['products'].find(db_query)
if matchingproducts:
return list(matchingproducts)
else:
return []
def add_product(producttobeadded):
db['products'].insert_one(producttobeadded)
def update_product(productnametobeupdated, updated_product):
filter={'name': productnametobeupdated}
update = {
'$set': updated_product
}
db['products'].update_one(filter=filter, update=update) | true | true |
f72c35766d755e29c14dd797ad91e44ab34914bc | 1,757 | py | Python | loading.py | hawkarcane/Hangman | 905640b087b747e6934ed7f18829b12784d0ed08 | [
"MIT"
] | null | null | null | loading.py | hawkarcane/Hangman | 905640b087b747e6934ed7f18829b12784d0ed08 | [
"MIT"
] | null | null | null | loading.py | hawkarcane/Hangman | 905640b087b747e6934ed7f18829b12784d0ed08 | [
"MIT"
] | null | null | null | #!/usr/bin/python
##### ~ http://stackoverflow.com/questions/7960600/python-tkinter-display-animated-gif-using-pil ~
## source of code can be found at the above web page, I have modified the code to suit my needs.
from Tkinter import *
from PIL import Image, ImageTk
class MyLabel(Label):
def __init__(self, master, filename):
im = Image.open(filename)
seq = []
try:
while 1:
seq.append(im.copy())
im.seek(len(seq)) # skip to next frame
except EOFError:
pass # we're done
try:
self.delay = im.info['duration']
except KeyError:
self.delay = 100
first = seq[0].convert('RGBA')
self.frames = [ImageTk.PhotoImage(first)]
Label.__init__(self, master, image=self.frames[0],
highlightthickness=0, bg='white')
temp = seq[0]
for image in seq[1:]:
temp.paste(image)
frame = temp.convert('RGBA')
self.frames.append(ImageTk.PhotoImage(frame))
self.idx = 0
self.cancel = self.after(self.delay, self.play)
def play(self):
self.config(image=self.frames[self.idx])
self.idx += 1
if self.idx == len(self.frames):
self.idx = 0
self.cancel = self.after(self.delay, self.play)
root = Tk()
anim = MyLabel(root, 'HangMan_img/loading/google.gif')
anim.place(x=140, y=90)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.config(bg='white')
root.overrideredirect(1)
x = screen_width / 2 - 500 / 2
y = screen_height / 2 - 400 / 2
root.geometry('%dx%d+%d+%d' % (500, 400, x, y))
anim.after(2000, root.destroy)
root.mainloop()
| 25.463768 | 98 | 0.59078 |
)
self.frames = [ImageTk.PhotoImage(first)]
Label.__init__(self, master, image=self.frames[0],
highlightthickness=0, bg='white')
temp = seq[0]
for image in seq[1:]:
temp.paste(image)
frame = temp.convert('RGBA')
self.frames.append(ImageTk.PhotoImage(frame))
self.idx = 0
self.cancel = self.after(self.delay, self.play)
def play(self):
self.config(image=self.frames[self.idx])
self.idx += 1
if self.idx == len(self.frames):
self.idx = 0
self.cancel = self.after(self.delay, self.play)
root = Tk()
anim = MyLabel(root, 'HangMan_img/loading/google.gif')
anim.place(x=140, y=90)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.config(bg='white')
root.overrideredirect(1)
x = screen_width / 2 - 500 / 2
y = screen_height / 2 - 400 / 2
root.geometry('%dx%d+%d+%d' % (500, 400, x, y))
anim.after(2000, root.destroy)
root.mainloop()
| true | true |
f72c37376707907e2c5dcac2d81f5c1e1aad10ec | 397 | py | Python | maillerApp/wsgi.py | Stblacq/Xmailer | 37cfd79f4c4b616fd449e78ef5587d1300090063 | [
"bzip2-1.0.6"
] | null | null | null | maillerApp/wsgi.py | Stblacq/Xmailer | 37cfd79f4c4b616fd449e78ef5587d1300090063 | [
"bzip2-1.0.6"
] | null | null | null | maillerApp/wsgi.py | Stblacq/Xmailer | 37cfd79f4c4b616fd449e78ef5587d1300090063 | [
"bzip2-1.0.6"
] | null | null | null | """
WSGI config for maillerApp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'maillerApp.settings')
application = get_wsgi_application()
| 23.352941 | 78 | 0.788413 |
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'maillerApp.settings')
application = get_wsgi_application()
| true | true |
f72c37cd1328712be9f8a12af2cea85e0bb1765d | 222,324 | py | Python | nova/tests/virt/libvirt/test_libvirt.py | melwitt/nova | 6c8706b70c3bb386e01742116306a0a7942956be | [
"Apache-2.0"
] | null | null | null | nova/tests/virt/libvirt/test_libvirt.py | melwitt/nova | 6c8706b70c3bb386e01742116306a0a7942956be | [
"Apache-2.0"
] | null | null | null | nova/tests/virt/libvirt/test_libvirt.py | melwitt/nova | 6c8706b70c3bb386e01742116306a0a7942956be | [
"Apache-2.0"
] | null | null | null | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2010 OpenStack Foundation
# Copyright 2012 University Of Minho
#
# 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 copy
import errno
import eventlet
import fixtures
import json
import mox
import os
import re
import shutil
import tempfile
from lxml import etree
from oslo.config import cfg
from xml.dom import minidom
from nova.api.ec2 import cloud
from nova.compute import flavors
from nova.compute import power_state
from nova.compute import task_states
from nova.compute import vm_mode
from nova.compute import vm_states
from nova import context
from nova import db
from nova import exception
from nova.openstack.common import fileutils
from nova.openstack.common import importutils
from nova.openstack.common import jsonutils
from nova.openstack.common import loopingcall
from nova.openstack.common import uuidutils
from nova import test
from nova.tests import fake_network
import nova.tests.image.fake
from nova.tests import matchers
from nova.tests.virt.libvirt import fake_libvirt_utils
from nova import utils
from nova import version
from nova.virt.disk import api as disk
from nova.virt import driver
from nova.virt import event as virtevent
from nova.virt import fake
from nova.virt import firewall as base_firewall
from nova.virt import images
from nova.virt.libvirt import blockinfo
from nova.virt.libvirt import config as vconfig
from nova.virt.libvirt import driver as libvirt_driver
from nova.virt.libvirt import firewall
from nova.virt.libvirt import imagebackend
from nova.virt.libvirt import utils as libvirt_utils
from nova.virt import netutils
try:
import libvirt
except ImportError:
import nova.tests.virt.libvirt.fakelibvirt as libvirt
libvirt_driver.libvirt = libvirt
CONF = cfg.CONF
CONF.import_opt('compute_manager', 'nova.service')
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')
CONF.import_opt('base_dir_name', 'nova.virt.libvirt.imagecache')
_fake_network_info = fake_network.fake_get_instance_nw_info
_fake_stub_out_get_nw_info = fake_network.stub_out_nw_api_get_instance_nw_info
_ipv4_like = fake_network.ipv4_like
def _concurrency(signal, wait, done, target):
signal.send()
wait.wait()
done.send()
class FakeVirDomainSnapshot(object):
def __init__(self, dom=None):
self.dom = dom
def delete(self, flags):
pass
class FakeVirtDomain(object):
def __init__(self, fake_xml=None, uuidstr=None):
self.uuidstr = uuidstr
if fake_xml:
self._fake_dom_xml = fake_xml
else:
self._fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
</devices>
</domain>
"""
def name(self):
return "fake-domain %s" % self
def info(self):
return [power_state.RUNNING, None, None, None, None]
def create(self):
pass
def managedSave(self, *args):
pass
def createWithFlags(self, launch_flags):
pass
def XMLDesc(self, *args):
return self._fake_dom_xml
def UUIDString(self):
return self.uuidstr
class CacheConcurrencyTestCase(test.TestCase):
def setUp(self):
super(CacheConcurrencyTestCase, self).setUp()
self.flags(instances_path=self.useFixture(fixtures.TempDir()).path)
# utils.synchronized() will create the lock_path for us if it
# doesn't already exist. It will also delete it when it's done,
# which can cause race conditions with the multiple threads we
# use for tests. So, create the path here so utils.synchronized()
# won't delete it out from under one of the threads.
self.lock_path = os.path.join(CONF.instances_path, 'locks')
fileutils.ensure_tree(self.lock_path)
def fake_exists(fname):
basedir = os.path.join(CONF.instances_path, CONF.base_dir_name)
if fname == basedir or fname == self.lock_path:
return True
return False
def fake_execute(*args, **kwargs):
pass
def fake_extend(image, size):
pass
self.stubs.Set(os.path, 'exists', fake_exists)
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(imagebackend.disk, 'extend', fake_extend)
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
def test_same_fname_concurrency(self):
# Ensures that the same fname cache runs at a sequentially.
uuid = uuidutils.generate_uuid()
backend = imagebackend.Backend(False)
wait1 = eventlet.event.Event()
done1 = eventlet.event.Event()
sig1 = eventlet.event.Event()
thr1 = eventlet.spawn(backend.image({'name': 'instance',
'uuid': uuid},
'name').cache,
_concurrency, 'fname', None,
signal=sig1, wait=wait1, done=done1)
eventlet.sleep(0)
# Thread 1 should run before thread 2.
sig1.wait()
wait2 = eventlet.event.Event()
done2 = eventlet.event.Event()
sig2 = eventlet.event.Event()
thr2 = eventlet.spawn(backend.image({'name': 'instance',
'uuid': uuid},
'name').cache,
_concurrency, 'fname', None,
signal=sig2, wait=wait2, done=done2)
wait2.send()
eventlet.sleep(0)
try:
self.assertFalse(done2.ready())
finally:
wait1.send()
done1.wait()
eventlet.sleep(0)
self.assertTrue(done2.ready())
# Wait on greenthreads to assert they didn't raise exceptions
# during execution
thr1.wait()
thr2.wait()
def test_different_fname_concurrency(self):
# Ensures that two different fname caches are concurrent.
uuid = uuidutils.generate_uuid()
backend = imagebackend.Backend(False)
wait1 = eventlet.event.Event()
done1 = eventlet.event.Event()
sig1 = eventlet.event.Event()
thr1 = eventlet.spawn(backend.image({'name': 'instance',
'uuid': uuid},
'name').cache,
_concurrency, 'fname2', None,
signal=sig1, wait=wait1, done=done1)
eventlet.sleep(0)
# Thread 1 should run before thread 2.
sig1.wait()
wait2 = eventlet.event.Event()
done2 = eventlet.event.Event()
sig2 = eventlet.event.Event()
thr2 = eventlet.spawn(backend.image({'name': 'instance',
'uuid': uuid},
'name').cache,
_concurrency, 'fname1', None,
signal=sig2, wait=wait2, done=done2)
eventlet.sleep(0)
# Wait for thread 2 to start.
sig2.wait()
wait2.send()
eventlet.sleep(0)
try:
self.assertTrue(done2.ready())
finally:
wait1.send()
eventlet.sleep(0)
# Wait on greenthreads to assert they didn't raise exceptions
# during execution
thr1.wait()
thr2.wait()
class FakeVolumeDriver(object):
def __init__(self, *args, **kwargs):
pass
def attach_volume(self, *args):
pass
def detach_volume(self, *args):
pass
def get_xml(self, *args):
return ""
class FakeConfigGuestDisk(object):
def __init__(self, *args, **kwargs):
self.source_type = None
self.driver_cache = None
class FakeConfigGuest(object):
def __init__(self, *args, **kwargs):
self.driver_cache = None
class LibvirtConnTestCase(test.TestCase):
def setUp(self):
super(LibvirtConnTestCase, self).setUp()
self.flags(fake_call=True)
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.get_admin_context()
self.flags(instances_path='')
self.flags(libvirt_snapshots_directory='')
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.libvirt_utils',
fake_libvirt_utils))
# Force libvirt to return a host UUID that matches the serial in
# nova.tests.fakelibvirt. This is necessary because the host UUID
# returned by libvirt becomes the serial whose value is checked for in
# test_xml_and_uri_* below.
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.LibvirtDriver.get_host_uuid',
lambda _: 'cef19ce0-0ca2-11df-855d-b19fbce37686'))
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
def fake_extend(image, size):
pass
self.stubs.Set(libvirt_driver.disk, 'extend', fake_extend)
class FakeConn():
def getCapabilities(self):
return """<capabilities>
<host><cpu><arch>x86_64</arch></cpu></host>
</capabilities>"""
def getLibVersion(self):
return (0 * 1000 * 1000) + (9 * 1000) + 11
self.conn = FakeConn()
self.stubs.Set(libvirt_driver.LibvirtDriver, '_connect',
lambda *a, **k: self.conn)
instance_type = db.instance_type_get(self.context, 5)
sys_meta = flavors.save_instance_type_info({}, instance_type)
nova.tests.image.fake.stub_out_image_service(self.stubs)
self.test_instance = {
'uuid': '32dfcb37-5af1-552b-357c-be8c3aa38310',
'memory_kb': '1024000',
'basepath': '/some/path',
'bridge_name': 'br100',
'vcpus': 2,
'project_id': 'fake',
'bridge': 'br101',
'image_ref': '155d900f-4e14-4e4c-a73d-069cbf4541e6',
'root_gb': 10,
'ephemeral_gb': 20,
'instance_type_id': '5', # m1.small
'extra_specs': {},
'system_metadata': sys_meta}
def tearDown(self):
nova.tests.image.fake.FakeImageService_reset()
super(LibvirtConnTestCase, self).tearDown()
def create_fake_libvirt_mock(self, **kwargs):
"""Defining mocks for LibvirtDriver(libvirt is not used)."""
# A fake libvirt.virConnect
class FakeLibvirtDriver(object):
def defineXML(self, xml):
return FakeVirtDomain()
# Creating mocks
volume_driver = ('iscsi=nova.tests.virt.libvirt.test_libvirt'
'.FakeVolumeDriver')
self.flags(libvirt_volume_drivers=[volume_driver])
fake = FakeLibvirtDriver()
# Customizing above fake if necessary
for key, val in kwargs.items():
fake.__setattr__(key, val)
self.flags(libvirt_vif_driver="nova.tests.fake_network.FakeVIFDriver")
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn = fake
def fake_lookup(self, instance_name):
return FakeVirtDomain()
def fake_execute(self, *args, **kwargs):
open(args[-1], "a").close()
def create_service(self, **kwargs):
service_ref = {'host': kwargs.get('host', 'dummy'),
'binary': 'nova-compute',
'topic': 'compute',
'report_count': 0}
return db.service_create(context.get_admin_context(), service_ref)
def test_get_connector(self):
initiator = 'fake.initiator.iqn'
ip = 'fakeip'
host = 'fakehost'
wwpns = ['100010604b019419']
wwnns = ['200010604b019419']
self.flags(my_ip=ip)
self.flags(host=host)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
expected = {
'ip': ip,
'initiator': initiator,
'host': host,
'wwpns': wwpns,
'wwnns': wwnns
}
volume = {
'id': 'fake'
}
result = conn.get_volume_connector(volume)
self.assertThat(expected, matchers.DictMatches(result))
def test_get_guest_config(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(cfg.acpi, True)
self.assertEquals(cfg.apic, True)
self.assertEquals(cfg.memory, 1024 * 1024 * 2)
self.assertEquals(cfg.vcpus, 1)
self.assertEquals(cfg.os_type, vm_mode.HVM)
self.assertEquals(cfg.os_boot_dev, "hd")
self.assertEquals(cfg.os_root, None)
self.assertEquals(len(cfg.devices), 7)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestInterface)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestInput)
self.assertEquals(type(cfg.devices[6]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(type(cfg.clock),
vconfig.LibvirtConfigGuestClock)
self.assertEquals(cfg.clock.offset, "utc")
self.assertEquals(len(cfg.clock.timers), 2)
self.assertEquals(type(cfg.clock.timers[0]),
vconfig.LibvirtConfigGuestTimer)
self.assertEquals(type(cfg.clock.timers[1]),
vconfig.LibvirtConfigGuestTimer)
self.assertEquals(cfg.clock.timers[0].name, "pit")
self.assertEquals(cfg.clock.timers[0].tickpolicy,
"delay")
self.assertEquals(cfg.clock.timers[1].name, "rtc")
self.assertEquals(cfg.clock.timers[1].tickpolicy,
"catchup")
def test_get_guest_config_with_two_nics(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 2),
None, disk_info)
self.assertEquals(cfg.acpi, True)
self.assertEquals(cfg.memory, 1024 * 1024 * 2)
self.assertEquals(cfg.vcpus, 1)
self.assertEquals(cfg.os_type, vm_mode.HVM)
self.assertEquals(cfg.os_boot_dev, "hd")
self.assertEquals(cfg.os_root, None)
self.assertEquals(len(cfg.devices), 8)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestInterface)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestInterface)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[6]),
vconfig.LibvirtConfigGuestInput)
self.assertEquals(type(cfg.devices[7]),
vconfig.LibvirtConfigGuestGraphics)
def test_get_guest_config_bug_1118829(self):
self.flags(libvirt_type='uml')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = {'disk_bus': 'virtio',
'cdrom_bus': 'ide',
'mapping': {u'vda': {'bus': 'virtio',
'type': 'disk',
'dev': u'vda'},
'root': {'bus': 'virtio',
'type': 'disk',
'dev': 'vda'}}}
# NOTE(jdg): For this specific test leave this blank
# This will exercise the failed code path still,
# and won't require fakes and stubs of the iscsi discovery
block_device_info = {}
cfg = conn.get_guest_config(instance_ref, [], None, disk_info,
None, block_device_info)
instance_ref = db.instance_get(self.context, instance_ref['id'])
self.assertEquals(instance_ref['root_device_name'], '/dev/vda')
def test_get_guest_config_with_root_device_name(self):
self.flags(libvirt_type='uml')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
block_device_info = {'root_device_name': '/dev/vdb'}
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref,
block_device_info)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info,
None, block_device_info)
self.assertEquals(cfg.acpi, False)
self.assertEquals(cfg.memory, 1024 * 1024 * 2)
self.assertEquals(cfg.vcpus, 1)
self.assertEquals(cfg.os_type, "uml")
self.assertEquals(cfg.os_boot_dev, None)
self.assertEquals(cfg.os_root, '/dev/vdb')
self.assertEquals(len(cfg.devices), 3)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestConsole)
def test_get_guest_config_with_block_device(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
conn_info = {'driver_volume_type': 'fake'}
info = {'block_device_mapping': [
{'connection_info': conn_info, 'mount_device': '/dev/vdc'},
{'connection_info': conn_info, 'mount_device': '/dev/vdd'}]}
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref, info)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info,
None, info)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(cfg.devices[2].target_dev, 'vdc')
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(cfg.devices[3].target_dev, 'vdd')
def test_get_guest_config_with_configdrive(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
# make configdrive.enabled_for() return True
instance_ref['config_drive'] = 'ANY_ID'
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(cfg.devices[2].target_dev, 'vdz')
def test_get_guest_config_with_vnc(self):
self.flags(libvirt_type='kvm',
vnc_enabled=True,
use_usb_tablet=False)
self.flags(enabled=False, group='spice')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(len(cfg.devices), 5)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(cfg.devices[4].type, "vnc")
def test_get_guest_config_with_vnc_and_tablet(self):
self.flags(libvirt_type='kvm',
vnc_enabled=True,
use_usb_tablet=True)
self.flags(enabled=False, group='spice')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(len(cfg.devices), 6)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestInput)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(cfg.devices[4].type, "tablet")
self.assertEquals(cfg.devices[5].type, "vnc")
def test_get_guest_config_with_spice_and_tablet(self):
self.flags(libvirt_type='kvm',
vnc_enabled=False,
use_usb_tablet=True)
self.flags(enabled=True,
agent_enabled=False,
group='spice')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(len(cfg.devices), 6)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestInput)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(cfg.devices[4].type, "tablet")
self.assertEquals(cfg.devices[5].type, "spice")
def test_get_guest_config_with_spice_and_agent(self):
self.flags(libvirt_type='kvm',
vnc_enabled=False,
use_usb_tablet=True)
self.flags(enabled=True,
agent_enabled=True,
group='spice')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(len(cfg.devices), 6)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestChannel)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(cfg.devices[4].target_name, "com.redhat.spice.0")
self.assertEquals(cfg.devices[5].type, "spice")
def test_get_guest_config_with_vnc_and_spice(self):
self.flags(libvirt_type='kvm',
vnc_enabled=True,
use_usb_tablet=True)
self.flags(enabled=True,
agent_enabled=True,
group='spice')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(len(cfg.devices), 8)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestInput)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestChannel)
self.assertEquals(type(cfg.devices[6]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(type(cfg.devices[7]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(cfg.devices[4].type, "tablet")
self.assertEquals(cfg.devices[5].target_name, "com.redhat.spice.0")
self.assertEquals(cfg.devices[6].type, "vnc")
self.assertEquals(cfg.devices[7].type, "spice")
def test_get_guest_cpu_config_none(self):
self.flags(libvirt_cpu_mode="none")
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(conf.cpu, None)
def test_get_guest_cpu_config_default_kvm(self):
self.flags(libvirt_type="kvm",
libvirt_cpu_mode=None)
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 11
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, "host-model")
self.assertEquals(conf.cpu.model, None)
def test_get_guest_cpu_config_default_uml(self):
self.flags(libvirt_type="uml",
libvirt_cpu_mode=None)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(conf.cpu, None)
def test_get_guest_cpu_config_default_lxc(self):
self.flags(libvirt_type="lxc",
libvirt_cpu_mode=None)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(conf.cpu, None)
def test_get_guest_cpu_config_host_passthrough_new(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 11
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="host-passthrough")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, "host-passthrough")
self.assertEquals(conf.cpu.model, None)
def test_get_guest_cpu_config_host_model_new(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 11
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="host-model")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, "host-model")
self.assertEquals(conf.cpu.model, None)
def test_get_guest_cpu_config_custom_new(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 11
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="custom")
self.flags(libvirt_cpu_model="Penryn")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, "custom")
self.assertEquals(conf.cpu.model, "Penryn")
def test_get_guest_cpu_config_host_passthrough_old(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 7
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="host-passthrough")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
self.assertRaises(exception.NovaException,
conn.get_guest_config,
instance_ref,
_fake_network_info(self.stubs, 1),
None,
disk_info)
def test_get_guest_cpu_config_host_model_old(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 7
# Ensure we have a predictable host CPU
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.model = "Opteron_G4"
cpu.vendor = "AMD"
cpu.features.append(vconfig.LibvirtConfigGuestCPUFeature("tm2"))
cpu.features.append(vconfig.LibvirtConfigGuestCPUFeature("ht"))
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
return caps
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
self.stubs.Set(libvirt_driver.LibvirtDriver,
"get_host_capabilities",
get_host_capabilities_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="host-model")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, None)
self.assertEquals(conf.cpu.model, "Opteron_G4")
self.assertEquals(conf.cpu.vendor, "AMD")
self.assertEquals(len(conf.cpu.features), 2)
self.assertEquals(conf.cpu.features[0].name, "tm2")
self.assertEquals(conf.cpu.features[1].name, "ht")
def test_get_guest_cpu_config_custom_old(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 7
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="custom")
self.flags(libvirt_cpu_model="Penryn")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, None)
self.assertEquals(conf.cpu.model, "Penryn")
def test_xml_and_uri_no_ramdisk_no_kernel(self):
instance_data = dict(self.test_instance)
self._check_xml_and_uri(instance_data,
expect_kernel=False, expect_ramdisk=False)
def test_xml_and_uri_no_ramdisk_no_kernel_xen_hvm(self):
instance_data = dict(self.test_instance)
instance_data.update({'vm_mode': vm_mode.HVM})
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, expect_xen_hvm=True)
def test_xml_and_uri_no_ramdisk_no_kernel_xen_pv(self):
instance_data = dict(self.test_instance)
instance_data.update({'vm_mode': vm_mode.XEN})
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, expect_xen_hvm=False,
xen_only=True)
def test_xml_and_uri_no_ramdisk(self):
instance_data = dict(self.test_instance)
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=True, expect_ramdisk=False)
def test_xml_and_uri_no_kernel(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=False, expect_ramdisk=False)
def test_xml_and_uri(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=True, expect_ramdisk=True)
def test_xml_and_uri_rescue(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=True,
expect_ramdisk=True, rescue=instance_data)
def test_xml_and_uri_rescue_no_kernel_no_ramdisk(self):
instance_data = dict(self.test_instance)
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, rescue=instance_data)
def test_xml_and_uri_rescue_no_kernel(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=True, rescue=instance_data)
def test_xml_and_uri_rescue_no_ramdisk(self):
instance_data = dict(self.test_instance)
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=True,
expect_ramdisk=False, rescue=instance_data)
def test_xml_uuid(self):
self._check_xml_and_uuid({"disk_format": "raw"})
def test_lxc_container_and_uri(self):
instance_data = dict(self.test_instance)
self._check_xml_and_container(instance_data)
def test_xml_disk_prefix(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_prefix(instance_data)
def test_xml_user_specified_disk_prefix(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_prefix(instance_data, 'sd')
def test_xml_disk_driver(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_driver(instance_data)
def test_xml_disk_bus_virtio(self):
self._check_xml_and_disk_bus({"disk_format": "raw"},
None,
(("disk", "virtio", "vda"),))
def test_xml_disk_bus_ide(self):
self._check_xml_and_disk_bus({"disk_format": "iso"},
None,
(("cdrom", "ide", "hda"),))
def test_xml_disk_bus_ide_and_virtio(self):
swap = {'device_name': '/dev/vdc',
'swap_size': 1}
ephemerals = [{'num': 0,
'virtual_name': 'ephemeral0',
'device_name': '/dev/vdb',
'size': 1}]
block_device_info = {
'swap': swap,
'ephemerals': ephemerals}
self._check_xml_and_disk_bus({"disk_format": "iso"},
block_device_info,
(("cdrom", "ide", "hda"),
("disk", "virtio", "vdb"),
("disk", "virtio", "vdc")))
def test_list_instances(self):
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByID = self.fake_lookup
libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 2
libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1]
libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: []
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instances = conn.list_instances()
# Only one should be listed, since domain with ID 0 must be skiped
self.assertEquals(len(instances), 1)
def test_list_defined_instances(self):
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByID = self.fake_lookup
libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1
libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0]
libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [1]
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instances = conn.list_instances()
# Only one defined domain should be listed
self.assertEquals(len(instances), 1)
def test_list_instances_when_instance_deleted(self):
def fake_lookup(instance_name):
raise libvirt.libvirtError("we deleted an instance!")
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup
libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1
libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1]
libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: []
self.mox.StubOutWithMock(libvirt.libvirtError, "get_error_code")
libvirt.libvirtError.get_error_code().AndReturn(
libvirt.VIR_ERR_NO_DOMAIN)
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instances = conn.list_instances()
# None should be listed, since we fake deleted the last one
self.assertEquals(len(instances), 0)
def test_get_all_block_devices(self):
xml = [
# NOTE(vish): id 0 is skipped
None,
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
</disk>
</devices>
</domain>
""",
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
</devices>
</domain>
""",
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/3'/>
</disk>
</devices>
</domain>
""",
]
def fake_lookup(id):
return FakeVirtDomain(xml[id])
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 4
libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: range(4)
libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
devices = conn.get_all_block_devices()
self.assertEqual(devices, ['/path/to/dev/1', '/path/to/dev/3'])
def test_get_disks(self):
xml = [
# NOTE(vish): id 0 is skipped
None,
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
</devices>
</domain>
""",
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
</devices>
</domain>
""",
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/3'/>
<target dev='vdb' bus='virtio'/>
</disk>
</devices>
</domain>
""",
]
def fake_lookup(id):
return FakeVirtDomain(xml[id])
def fake_lookup_name(name):
return FakeVirtDomain(xml[1])
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 4
libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: range(4)
libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: []
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
devices = conn.get_disks(conn.list_instances()[0])
self.assertEqual(devices, ['vda', 'vdb'])
def test_snapshot_in_ami_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./')
# Start test
image_service = nova.tests.image.fake.FakeImageService()
# Assign different image_ref from nova/images/fakes for testing ami
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77'
# Assuming that base image already exists in image_service
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
# Create new image. It will be updated in snapshot method
# To work with it from snapshot, the single image_service is needed
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
libvirt_driver.libvirt_utils.disk_type = "qcow2"
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'ami')
self.assertEquals(snapshot['name'], snapshot_name)
def test_lxc_snapshot_in_ami_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./',
libvirt_type='lxc')
# Start test
image_service = nova.tests.image.fake.FakeImageService()
# Assign different image_ref from nova/images/fakes for testing ami
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77'
# Assuming that base image already exists in image_service
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
# Create new image. It will be updated in snapshot method
# To work with it from snapshot, the single image_service is needed
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
libvirt_driver.libvirt_utils.disk_type = "qcow2"
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'ami')
self.assertEquals(snapshot['name'], snapshot_name)
def test_snapshot_in_raw_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./')
# Start test
image_service = nova.tests.image.fake.FakeImageService()
# Assuming that base image already exists in image_service
instance_ref = db.instance_create(self.context, self.test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
# Create new image. It will be updated in snapshot method
# To work with it from snapshot, the single image_service is needed
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.stubs.Set(libvirt_driver.libvirt_utils, 'disk_type', 'raw')
def convert_image(source, dest, out_format):
libvirt_driver.libvirt_utils.files[dest] = ''
self.stubs.Set(images, 'convert_image', convert_image)
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'raw')
self.assertEquals(snapshot['name'], snapshot_name)
def test_lxc_snapshot_in_raw_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./',
libvirt_type='lxc')
# Start test
image_service = nova.tests.image.fake.FakeImageService()
# Assuming that base image already exists in image_service
instance_ref = db.instance_create(self.context, self.test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
# Create new image. It will be updated in snapshot method
# To work with it from snapshot, the single image_service is needed
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.stubs.Set(libvirt_driver.libvirt_utils, 'disk_type', 'raw')
def convert_image(source, dest, out_format):
libvirt_driver.libvirt_utils.files[dest] = ''
self.stubs.Set(images, 'convert_image', convert_image)
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'raw')
self.assertEquals(snapshot['name'], snapshot_name)
def test_snapshot_in_qcow2_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(snapshot_image_format='qcow2',
libvirt_snapshots_directory='./')
# Start test
image_service = nova.tests.image.fake.FakeImageService()
# Assuming that base image already exists in image_service
instance_ref = db.instance_create(self.context, self.test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
# Create new image. It will be updated in snapshot method
# To work with it from snapshot, the single image_service is needed
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
libvirt_driver.libvirt_utils.disk_type = "qcow2"
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'qcow2')
self.assertEquals(snapshot['name'], snapshot_name)
def test_lxc_snapshot_in_qcow2_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(snapshot_image_format='qcow2',
libvirt_snapshots_directory='./',
libvirt_type='lxc')
# Start test
image_service = nova.tests.image.fake.FakeImageService()
# Assuming that base image already exists in image_service
instance_ref = db.instance_create(self.context, self.test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
# Create new image. It will be updated in snapshot method
# To work with it from snapshot, the single image_service is needed
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
libvirt_driver.libvirt_utils.disk_type = "qcow2"
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'qcow2')
self.assertEquals(snapshot['name'], snapshot_name)
def test_snapshot_no_image_architecture(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./')
# Start test
image_service = nova.tests.image.fake.FakeImageService()
# Assign different image_ref from nova/images/fakes for
# testing different base image
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6'
# Assuming that base image already exists in image_service
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
# Create new image. It will be updated in snapshot method
# To work with it from snapshot, the single image_service is needed
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['name'], snapshot_name)
def test_lxc_snapshot_no_image_architecture(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./',
libvirt_type='lxc')
# Start test
image_service = nova.tests.image.fake.FakeImageService()
# Assign different image_ref from nova/images/fakes for
# testing different base image
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6'
# Assuming that base image already exists in image_service
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
# Create new image. It will be updated in snapshot method
# To work with it from snapshot, the single image_service is needed
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['name'], snapshot_name)
def test_snapshot_no_original_image(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./')
# Start test
image_service = nova.tests.image.fake.FakeImageService()
# Assign a non-existent image
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = '661122aa-1234-dede-fefe-babababababa'
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['name'], snapshot_name)
def test_lxc_snapshot_no_original_image(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./',
libvirt_type='lxc')
# Start test
image_service = nova.tests.image.fake.FakeImageService()
# Assign a non-existent image
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = '661122aa-1234-dede-fefe-babababababa'
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['name'], snapshot_name)
def test_snapshot_metadata_image(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./')
image_service = nova.tests.image.fake.FakeImageService()
# Assign an image with an architecture defined (x86_64)
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = 'a440c04b-79fa-479c-bed1-0b816eaec379'
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id),
'architecture': 'fake_arch',
'key_a': 'value_a',
'key_b': 'value_b'}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['properties']['architecture'], 'fake_arch')
self.assertEquals(snapshot['properties']['key_a'], 'value_a')
self.assertEquals(snapshot['properties']['key_b'], 'value_b')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['name'], snapshot_name)
def test_attach_invalid_volume_type(self):
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.VolumeDriverNotFound,
conn.attach_volume,
{"driver_volume_type": "badtype"},
{"name": "fake-instance"},
"/dev/sda")
def test_multi_nic(self):
instance_data = dict(self.test_instance)
network_info = _fake_network_info(self.stubs, 2)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, instance_data)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = conn.to_xml(instance_ref, network_info, disk_info)
tree = etree.fromstring(xml)
interfaces = tree.findall("./devices/interface")
self.assertEquals(len(interfaces), 2)
self.assertEquals(interfaces[0].get('type'), 'bridge')
def _check_xml_and_container(self, instance):
user_context = context.RequestContext(self.user_id,
self.project_id)
instance_ref = db.instance_create(user_context, instance)
self.flags(libvirt_type='lxc')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEquals(conn.uri(), 'lxc:///')
network_info = _fake_network_info(self.stubs, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = conn.to_xml(instance_ref, network_info, disk_info)
tree = etree.fromstring(xml)
check = [
(lambda t: t.find('.').get('type'), 'lxc'),
(lambda t: t.find('./os/type').text, 'exe'),
(lambda t: t.find('./devices/filesystem/target').get('dir'), '/')]
for i, (check, expected_result) in enumerate(check):
self.assertEqual(check(tree),
expected_result,
'%s failed common check %d' % (xml, i))
target = tree.find('./devices/filesystem/source').get('dir')
self.assertTrue(len(target) > 0)
def _check_xml_and_disk_prefix(self, instance, prefix=None):
user_context = context.RequestContext(self.user_id,
self.project_id)
instance_ref = db.instance_create(user_context, instance)
def _get_prefix(p, default):
if p:
return p + 'a'
return default
type_disk_map = {
'qemu': [
(lambda t: t.find('.').get('type'), 'qemu'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'vda'))],
'xen': [
(lambda t: t.find('.').get('type'), 'xen'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'sda'))],
'kvm': [
(lambda t: t.find('.').get('type'), 'kvm'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'vda'))],
'uml': [
(lambda t: t.find('.').get('type'), 'uml'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'ubda'))]
}
for (libvirt_type, checks) in type_disk_map.iteritems():
self.flags(libvirt_type=libvirt_type)
if prefix:
self.flags(libvirt_disk_prefix=prefix)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
network_info = _fake_network_info(self.stubs, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = conn.to_xml(instance_ref, network_info, disk_info)
tree = etree.fromstring(xml)
for i, (check, expected_result) in enumerate(checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed check %d' %
(check(tree), expected_result, i))
def _check_xml_and_disk_driver(self, image_meta):
os_open = os.open
directio_supported = True
def os_open_stub(path, flags, *args, **kwargs):
if flags & os.O_DIRECT:
if not directio_supported:
raise OSError(errno.EINVAL,
'%s: %s' % (os.strerror(errno.EINVAL), path))
flags &= ~os.O_DIRECT
return os_open(path, flags, *args, **kwargs)
self.stubs.Set(os, 'open', os_open_stub)
def connection_supports_direct_io_stub(*args, **kwargs):
return directio_supported
self.stubs.Set(libvirt_driver.LibvirtDriver,
'_supports_direct_io', connection_supports_direct_io_stub)
user_context = context.RequestContext(self.user_id, self.project_id)
instance_ref = db.instance_create(user_context, self.test_instance)
network_info = _fake_network_info(self.stubs, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = drv.to_xml(instance_ref, network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
disks = tree.findall('./devices/disk/driver')
for disk in disks:
self.assertEqual(disk.get("cache"), "none")
directio_supported = False
# The O_DIRECT availability is cached on first use in
# LibvirtDriver, hence we re-create it here
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = drv.to_xml(instance_ref, network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
disks = tree.findall('./devices/disk/driver')
for disk in disks:
self.assertEqual(disk.get("cache"), "writethrough")
def _check_xml_and_disk_bus(self, image_meta,
block_device_info, wantConfig):
user_context = context.RequestContext(self.user_id, self.project_id)
instance_ref = db.instance_create(user_context, self.test_instance)
network_info = _fake_network_info(self.stubs, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref,
block_device_info,
image_meta)
xml = drv.to_xml(instance_ref, network_info, disk_info, image_meta,
block_device_info=block_device_info)
tree = etree.fromstring(xml)
got_disks = tree.findall('./devices/disk')
got_disk_targets = tree.findall('./devices/disk/target')
for i in range(len(wantConfig)):
want_device_type = wantConfig[i][0]
want_device_bus = wantConfig[i][1]
want_device_dev = wantConfig[i][2]
got_device_type = got_disks[i].get('device')
got_device_bus = got_disk_targets[i].get('bus')
got_device_dev = got_disk_targets[i].get('dev')
self.assertEqual(got_device_type, want_device_type)
self.assertEqual(got_device_bus, want_device_bus)
self.assertEqual(got_device_dev, want_device_dev)
def _check_xml_and_uuid(self, image_meta):
user_context = context.RequestContext(self.user_id, self.project_id)
instance_ref = db.instance_create(user_context, self.test_instance)
network_info = _fake_network_info(self.stubs, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = drv.to_xml(instance_ref, network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
self.assertEqual(tree.find('./uuid').text,
instance_ref['uuid'])
def _check_xml_and_uri(self, instance, expect_ramdisk, expect_kernel,
rescue=None, expect_xen_hvm=False, xen_only=False):
user_context = context.RequestContext(self.user_id, self.project_id)
instance_ref = db.instance_create(user_context, instance)
network_ref = db.project_get_networks(context.get_admin_context(),
self.project_id)[0]
type_uri_map = {'qemu': ('qemu:///system',
[(lambda t: t.find('.').get('type'), 'qemu'),
(lambda t: t.find('./os/type').text,
vm_mode.HVM),
(lambda t: t.find('./devices/emulator'), None)]),
'kvm': ('qemu:///system',
[(lambda t: t.find('.').get('type'), 'kvm'),
(lambda t: t.find('./os/type').text,
vm_mode.HVM),
(lambda t: t.find('./devices/emulator'), None)]),
'uml': ('uml:///system',
[(lambda t: t.find('.').get('type'), 'uml'),
(lambda t: t.find('./os/type').text,
vm_mode.UML)]),
'xen': ('xen:///',
[(lambda t: t.find('.').get('type'), 'xen'),
(lambda t: t.find('./os/type').text,
vm_mode.XEN)])}
if expect_xen_hvm or xen_only:
hypervisors_to_check = ['xen']
else:
hypervisors_to_check = ['qemu', 'kvm', 'xen']
if expect_xen_hvm:
type_uri_map = {}
type_uri_map['xen'] = ('xen:///',
[(lambda t: t.find('.').get('type'),
'xen'),
(lambda t: t.find('./os/type').text,
vm_mode.HVM)])
for hypervisor_type in hypervisors_to_check:
check_list = type_uri_map[hypervisor_type][1]
if rescue:
suffix = '.rescue'
else:
suffix = ''
if expect_kernel:
check = (lambda t: t.find('./os/kernel').text.split(
'/')[1], 'kernel' + suffix)
else:
check = (lambda t: t.find('./os/kernel'), None)
check_list.append(check)
# Hypervisors that only support vm_mode.HVM should
# not produce configuration that results in kernel
# arguments
if not expect_kernel and hypervisor_type in ['qemu', 'kvm']:
check = (lambda t: t.find('./os/root'), None)
check_list.append(check)
check = (lambda t: t.find('./os/cmdline'), None)
check_list.append(check)
if expect_ramdisk:
check = (lambda t: t.find('./os/initrd').text.split(
'/')[1], 'ramdisk' + suffix)
else:
check = (lambda t: t.find('./os/initrd'), None)
check_list.append(check)
if hypervisor_type in ['qemu', 'kvm']:
xpath = "./sysinfo/system/entry"
check = (lambda t: t.findall(xpath)[0].get("name"),
"manufacturer")
check_list.append(check)
check = (lambda t: t.findall(xpath)[0].text,
version.vendor_string())
check_list.append(check)
check = (lambda t: t.findall(xpath)[1].get("name"),
"product")
check_list.append(check)
check = (lambda t: t.findall(xpath)[1].text,
version.product_string())
check_list.append(check)
check = (lambda t: t.findall(xpath)[2].get("name"),
"version")
check_list.append(check)
# NOTE(sirp): empty strings don't roundtrip in lxml (they are
# converted to None), so we need an `or ''` to correct for that
check = (lambda t: t.findall(xpath)[2].text or '',
version.version_string_with_package())
check_list.append(check)
check = (lambda t: t.findall(xpath)[3].get("name"),
"serial")
check_list.append(check)
check = (lambda t: t.findall(xpath)[3].text,
"cef19ce0-0ca2-11df-855d-b19fbce37686")
check_list.append(check)
check = (lambda t: t.findall(xpath)[4].get("name"),
"uuid")
check_list.append(check)
check = (lambda t: t.findall(xpath)[4].text,
instance['uuid'])
check_list.append(check)
if hypervisor_type in ['qemu', 'kvm']:
check = (lambda t: t.findall('./devices/serial')[0].get(
'type'), 'file')
check_list.append(check)
check = (lambda t: t.findall('./devices/serial')[1].get(
'type'), 'pty')
check_list.append(check)
check = (lambda t: t.findall('./devices/serial/source')[0].get(
'path').split('/')[1], 'console.log')
check_list.append(check)
else:
check = (lambda t: t.find('./devices/console').get(
'type'), 'pty')
check_list.append(check)
common_checks = [
(lambda t: t.find('.').tag, 'domain'),
(lambda t: t.find('./memory').text, '2097152')]
if rescue:
common_checks += [
(lambda t: t.findall('./devices/disk/source')[0].get(
'file').split('/')[1], 'disk.rescue'),
(lambda t: t.findall('./devices/disk/source')[1].get(
'file').split('/')[1], 'disk')]
else:
common_checks += [(lambda t: t.findall(
'./devices/disk/source')[0].get('file').split('/')[1],
'disk')]
common_checks += [(lambda t: t.findall(
'./devices/disk/source')[1].get('file').split('/')[1],
'disk.local')]
for (libvirt_type, (expected_uri, checks)) in type_uri_map.iteritems():
self.flags(libvirt_type=libvirt_type)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEquals(conn.uri(), expected_uri)
network_info = _fake_network_info(self.stubs, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref,
rescue=rescue)
xml = conn.to_xml(instance_ref, network_info, disk_info,
rescue=rescue)
tree = etree.fromstring(xml)
for i, (check, expected_result) in enumerate(checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed check %d' %
(check(tree), expected_result, i))
for i, (check, expected_result) in enumerate(common_checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed common check %d' %
(check(tree), expected_result, i))
filterref = './devices/interface/filterref'
(network, mapping) = network_info[0]
nic_id = mapping['mac'].replace(':', '')
fw = firewall.NWFilterFirewall(fake.FakeVirtAPI(), conn)
instance_filter_name = fw._instance_filter_name(instance_ref,
nic_id)
self.assertEqual(tree.find(filterref).get('filter'),
instance_filter_name)
# This test is supposed to make sure we don't
# override a specifically set uri
#
# Deliberately not just assigning this string to CONF.libvirt_uri and
# checking against that later on. This way we make sure the
# implementation doesn't fiddle around with the CONF.
testuri = 'something completely different'
self.flags(libvirt_uri=testuri)
for (libvirt_type, (expected_uri, checks)) in type_uri_map.iteritems():
self.flags(libvirt_type=libvirt_type)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEquals(conn.uri(), testuri)
db.instance_destroy(user_context, instance_ref['uuid'])
def test_ensure_filtering_rules_for_instance_timeout(self):
# ensure_filtering_fules_for_instance() finishes with timeout.
# Preparing mocks
def fake_none(self, *args):
return
def fake_raise(self):
raise libvirt.libvirtError('ERR')
class FakeTime(object):
def __init__(self):
self.counter = 0
def sleep(self, t):
self.counter += t
fake_timer = FakeTime()
# _fake_network_info must be called before create_fake_libvirt_mock(),
# as _fake_network_info calls importutils.import_class() and
# create_fake_libvirt_mock() mocks importutils.import_class().
network_info = _fake_network_info(self.stubs, 1)
self.create_fake_libvirt_mock()
instance_ref = db.instance_create(self.context, self.test_instance)
# Start test
self.mox.ReplayAll()
try:
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn.firewall_driver,
'setup_basic_filtering',
fake_none)
self.stubs.Set(conn.firewall_driver,
'prepare_instance_filter',
fake_none)
self.stubs.Set(conn.firewall_driver,
'instance_filter_exists',
fake_none)
conn.ensure_filtering_rules_for_instance(instance_ref,
network_info,
time_module=fake_timer)
except exception.NovaException, e:
msg = ('The firewall filter for %s does not exist' %
instance_ref['name'])
c1 = (0 <= str(e).find(msg))
self.assertTrue(c1)
self.assertEqual(29, fake_timer.counter, "Didn't wait the expected "
"amount of time")
db.instance_destroy(self.context, instance_ref['uuid'])
def test_check_can_live_migrate_dest_all_pass_with_block_migration(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest = "fake_host_2"
src = instance_ref['host']
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'disk_available_least': 400,
'cpu_info': 'asdf',
}
filename = "file"
self.mox.StubOutWithMock(conn, '_create_shared_storage_test_file')
self.mox.StubOutWithMock(conn, '_compare_cpu')
# _check_cpu_match
conn._compare_cpu("asdf")
# mounted_on_same_shared_storage
conn._create_shared_storage_test_file().AndReturn(filename)
self.mox.ReplayAll()
return_value = conn.check_can_live_migrate_destination(self.context,
instance_ref, compute_info, compute_info, True)
self.assertThat({"filename": "file",
'disk_available_mb': 409600,
"disk_over_commit": False,
"block_migration": True},
matchers.DictMatches(return_value))
def test_check_can_live_migrate_dest_all_pass_no_block_migration(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest = "fake_host_2"
src = instance_ref['host']
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'cpu_info': 'asdf'}
filename = "file"
self.mox.StubOutWithMock(conn, '_create_shared_storage_test_file')
self.mox.StubOutWithMock(conn, '_compare_cpu')
# _check_cpu_match
conn._compare_cpu("asdf")
# mounted_on_same_shared_storage
conn._create_shared_storage_test_file().AndReturn(filename)
self.mox.ReplayAll()
return_value = conn.check_can_live_migrate_destination(self.context,
instance_ref, compute_info, compute_info, False)
self.assertThat({"filename": "file",
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": None},
matchers.DictMatches(return_value))
def test_check_can_live_migrate_dest_incompatible_cpu_raises(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest = "fake_host_2"
src = instance_ref['host']
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'cpu_info': 'asdf'}
self.mox.StubOutWithMock(conn, '_compare_cpu')
conn._compare_cpu("asdf").AndRaise(exception.InvalidCPUInfo(
reason='foo')
)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidCPUInfo,
conn.check_can_live_migrate_destination,
self.context, instance_ref,
compute_info, compute_info, False)
def test_check_can_live_migrate_dest_cleanup_works_correctly(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": True,
"disk_over_commit": False,
"disk_available_mb": 1024}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, '_cleanup_shared_storage_test_file')
conn._cleanup_shared_storage_test_file("file")
self.mox.ReplayAll()
conn.check_can_live_migrate_destination_cleanup(self.context,
dest_check_data)
def test_check_can_live_migrate_source_works_correctly(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": True,
"disk_over_commit": False,
"disk_available_mb": 1024}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(False)
self.mox.StubOutWithMock(conn, "_assert_dest_node_has_enough_disk")
conn._assert_dest_node_has_enough_disk(self.context, instance_ref,
dest_check_data['disk_available_mb'],
False)
self.mox.ReplayAll()
conn.check_can_live_migrate_source(self.context, instance_ref,
dest_check_data)
def test_check_can_live_migrate_source_vol_backed_works_correctly(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": 1024,
"is_volume_backed": True}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(False)
self.mox.ReplayAll()
ret = conn.check_can_live_migrate_source(self.context, instance_ref,
dest_check_data)
self.assertTrue(type(ret) == dict)
self.assertTrue('is_shared_storage' in ret)
def test_check_can_live_migrate_source_vol_backed_fails(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": 1024,
"is_volume_backed": False}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(False)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidSharedStorage,
conn.check_can_live_migrate_source, self.context,
instance_ref, dest_check_data)
def test_check_can_live_migrate_dest_fail_shared_storage_with_blockm(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": True,
"disk_over_commit": False,
'disk_available_mb': 1024}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(True)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidLocalStorage,
conn.check_can_live_migrate_source,
self.context, instance_ref, dest_check_data)
def test_check_can_live_migrate_no_shared_storage_no_blck_mig_raises(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": False,
"disk_over_commit": False,
'disk_available_mb': 1024}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(False)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidSharedStorage,
conn.check_can_live_migrate_source,
self.context, instance_ref, dest_check_data)
def test_check_can_live_migrate_source_with_dest_not_enough_disk(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest = "fake_host_2"
src = instance_ref['host']
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(False)
self.mox.StubOutWithMock(conn, "get_instance_disk_info")
conn.get_instance_disk_info(instance_ref["name"]).AndReturn(
'[{"virt_disk_size":2}]')
dest_check_data = {"filename": "file",
"disk_available_mb": 0,
"block_migration": True,
"disk_over_commit": False}
self.mox.ReplayAll()
self.assertRaises(exception.MigrationError,
conn.check_can_live_migrate_source,
self.context, instance_ref, dest_check_data)
def test_live_migration_raises_exception(self):
# Confirms recover method is called when exceptions are raised.
# Preparing data
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = {'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE}
instance_ref = db.instance_create(self.context, self.test_instance)
instance_ref = db.instance_update(self.context, instance_ref['uuid'],
instance_dict)
# Preparing mocks
vdmock = self.mox.CreateMock(libvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "migrateToURI")
_bandwidth = CONF.live_migration_bandwidth
vdmock.migrateToURI(CONF.live_migration_uri % 'dest',
mox.IgnoreArg(),
None,
_bandwidth).AndRaise(libvirt.libvirtError('ERR'))
def fake_lookup(instance_name):
if instance_name == instance_ref['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
self.mox.StubOutWithMock(self.compute, "_rollback_live_migration")
self.compute._rollback_live_migration(self.context, instance_ref,
'dest', False)
#start test
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(libvirt.libvirtError,
conn._live_migration,
self.context, instance_ref, 'dest', False,
self.compute._rollback_live_migration)
instance_ref = db.instance_get(self.context, instance_ref['id'])
self.assertTrue(instance_ref['vm_state'] == vm_states.ACTIVE)
self.assertTrue(instance_ref['power_state'] == power_state.RUNNING)
db.instance_destroy(self.context, instance_ref['uuid'])
def test_pre_live_migration_works_correctly_mocked(self):
# Creating testdata
vol = {'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
class FakeNetworkInfo():
def fixed_ips(self):
return ["test_ip_addr"]
inst_ref = {'id': 'foo'}
c = context.get_admin_context()
nw_info = FakeNetworkInfo()
# Creating mocks
self.mox.StubOutWithMock(driver, "block_device_info_get_mapping")
driver.block_device_info_get_mapping(vol
).AndReturn(vol['block_device_mapping'])
self.mox.StubOutWithMock(conn, "volume_driver_method")
for v in vol['block_device_mapping']:
disk_info = {
'bus': "scsi",
'dev': v['mount_device'].rpartition("/")[2],
'type': "disk"
}
conn.volume_driver_method('connect_volume',
v['connection_info'],
disk_info)
self.mox.StubOutWithMock(conn, 'plug_vifs')
conn.plug_vifs(mox.IsA(inst_ref), nw_info)
self.mox.ReplayAll()
result = conn.pre_live_migration(c, inst_ref, vol, nw_info)
self.assertEqual(result, None)
def test_pre_live_migration_vol_backed_works_correctly_mocked(self):
# Creating testdata, using temp dir.
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
vol = {'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
class FakeNetworkInfo():
def fixed_ips(self):
return ["test_ip_addr"]
inst_ref = db.instance_create(self.context, self.test_instance)
c = context.get_admin_context()
nw_info = FakeNetworkInfo()
# Creating mocks
self.mox.StubOutWithMock(conn, "volume_driver_method")
for v in vol['block_device_mapping']:
disk_info = {
'bus': "scsi",
'dev': v['mount_device'].rpartition("/")[2],
'type': "disk"
}
conn.volume_driver_method('connect_volume',
v['connection_info'],
disk_info)
self.mox.StubOutWithMock(conn, 'plug_vifs')
conn.plug_vifs(mox.IsA(inst_ref), nw_info)
self.mox.ReplayAll()
migrate_data = {'is_shared_storage': False,
'is_volume_backed': True,
'block_migration': False
}
ret = conn.pre_live_migration(c, inst_ref, vol, nw_info,
migrate_data)
self.assertEqual(ret, None)
self.assertTrue(os.path.exists('%s/%s/' % (tmpdir,
inst_ref['uuid'])))
db.instance_destroy(self.context, inst_ref['uuid'])
def test_pre_block_migration_works_correctly(self):
# Replace instances_path since this testcase creates tmpfile
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
# Test data
instance_ref = db.instance_create(self.context, self.test_instance)
dummy_info = [{'path': '%s/disk' % tmpdir,
'disk_size': 10737418240,
'type': 'raw',
'backing_file': ''},
{'backing_file': 'otherdisk_1234567',
'path': '%s/otherdisk' % tmpdir,
'virt_disk_size': 10737418240}]
dummyjson = json.dumps(dummy_info)
# qemu-img should be mockd since test environment might not have
# large disk space.
self.mox.StubOutWithMock(imagebackend.Image, 'cache')
imagebackend.Image.cache(context=mox.IgnoreArg(),
fetch_func=mox.IgnoreArg(),
filename='otherdisk',
image_id=self.test_instance['image_ref'],
project_id='fake',
size=10737418240L,
user_id=None).AndReturn(None)
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.pre_block_migration(self.context, instance_ref,
dummyjson)
self.assertTrue(os.path.exists('%s/%s/' %
(tmpdir, instance_ref['uuid'])))
db.instance_destroy(self.context, instance_ref['uuid'])
def test_get_instance_disk_info_works_correctly(self):
# Test data
instance_ref = db.instance_create(self.context, self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/test/disk.local'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"</devices></domain>")
# Preparing mocks
vdmock = self.mox.CreateMock(libvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance_ref['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
GB = 1024 * 1024 * 1024
fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * GB
fake_libvirt_utils.disk_sizes['/test/disk.local'] = 20 * GB
fake_libvirt_utils.disk_backing_files['/test/disk.local'] = 'file'
self.mox.StubOutWithMock(os.path, "getsize")
os.path.getsize('/test/disk').AndReturn((10737418240))
os.path.getsize('/test/disk.local').AndReturn((3328599655))
ret = ("image: /test/disk\n"
"file format: raw\n"
"virtual size: 20G (21474836480 bytes)\n"
"disk size: 3.1G\n"
"cluster_size: 2097152\n"
"backing file: /test/dummy (actual path: /backing/file)\n")
self.mox.StubOutWithMock(os.path, "exists")
os.path.exists('/test/disk.local').AndReturn(True)
self.mox.StubOutWithMock(utils, "execute")
utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
'/test/disk.local').AndReturn((ret, ''))
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
info = conn.get_instance_disk_info(instance_ref['name'])
info = jsonutils.loads(info)
self.assertEquals(info[0]['type'], 'raw')
self.assertEquals(info[0]['path'], '/test/disk')
self.assertEquals(info[0]['disk_size'], 10737418240)
self.assertEquals(info[0]['backing_file'], "")
self.assertEquals(info[0]['over_committed_disk_size'], 0)
self.assertEquals(info[1]['type'], 'qcow2')
self.assertEquals(info[1]['path'], '/test/disk.local')
self.assertEquals(info[1]['virt_disk_size'], 21474836480)
self.assertEquals(info[1]['backing_file'], "file")
self.assertEquals(info[1]['over_committed_disk_size'], 18146236825)
db.instance_destroy(self.context, instance_ref['uuid'])
def test_spawn_with_network_info(self):
# Preparing mocks
def fake_none(*args, **kwargs):
return
def fake_getLibVersion():
return 9007
def fake_getCapabilities():
return """
<capabilities>
<host>
<uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
<cpu>
<arch>x86_64</arch>
<model>Penryn</model>
<vendor>Intel</vendor>
<topology sockets='1' cores='2' threads='1'/>
<feature name='xtpr'/>
</cpu>
</host>
</capabilities>
"""
# _fake_network_info must be called before create_fake_libvirt_mock(),
# as _fake_network_info calls importutils.import_class() and
# create_fake_libvirt_mock() mocks importutils.import_class().
network_info = _fake_network_info(self.stubs, 1)
self.create_fake_libvirt_mock(getLibVersion=fake_getLibVersion,
getCapabilities=fake_getCapabilities)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456 # we send an int to test sha1 call
instance_type = db.instance_type_get(self.context,
instance_ref['instance_type_id'])
sys_meta = flavors.save_instance_type_info({}, instance_type)
instance_ref['system_metadata'] = sys_meta
instance = db.instance_create(self.context, instance_ref)
# Mock out the get_info method of the LibvirtDriver so that the polling
# in the spawn method of the LibvirtDriver returns immediately
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, 'get_info')
libvirt_driver.LibvirtDriver.get_info(instance
).AndReturn({'state': power_state.RUNNING})
# Start test
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn.firewall_driver,
'setup_basic_filtering',
fake_none)
self.stubs.Set(conn.firewall_driver,
'prepare_instance_filter',
fake_none)
self.stubs.Set(imagebackend.Image,
'cache',
fake_none)
conn.spawn(self.context, instance, None, [], 'herp',
network_info=network_info)
path = os.path.join(CONF.instances_path, instance['name'])
if os.path.isdir(path):
shutil.rmtree(path)
path = os.path.join(CONF.instances_path, CONF.base_dir_name)
if os.path.isdir(path):
shutil.rmtree(os.path.join(CONF.instances_path,
CONF.base_dir_name))
def test_spawn_without_image_meta(self):
self.create_image_called = False
def fake_none(*args, **kwargs):
return
def fake_create_image(*args, **kwargs):
self.create_image_called = True
def fake_get_info(instance):
return {'state': power_state.RUNNING}
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance = db.instance_create(self.context, instance_ref)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, 'to_xml', fake_none)
self.stubs.Set(conn, '_create_image', fake_create_image)
self.stubs.Set(conn, '_create_domain_and_network', fake_none)
self.stubs.Set(conn, 'get_info', fake_get_info)
conn.spawn(self.context, instance, None, [], None)
self.assertTrue(self.create_image_called)
conn.spawn(self.context,
instance,
{'id': instance['image_ref']},
[],
None)
self.assertTrue(self.create_image_called)
def test_spawn_from_volume_calls_cache(self):
self.cache_called_for_disk = False
def fake_none(*args, **kwargs):
return
def fake_cache(*args, **kwargs):
if kwargs.get('image_id') == 'my_fake_image':
self.cache_called_for_disk = True
def fake_get_info(instance):
return {'state': power_state.RUNNING}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, 'to_xml', fake_none)
self.stubs.Set(imagebackend.Image, 'cache', fake_cache)
self.stubs.Set(conn, '_create_domain_and_network', fake_none)
self.stubs.Set(conn, 'get_info', fake_get_info)
block_device_info = {'root_device_name': '/dev/vda',
'block_device_mapping': [
{'mount_device': 'vda'}]}
# Volume-backed instance created without image
instance_ref = self.test_instance
instance_ref['image_ref'] = ''
instance_ref['root_device_name'] = '/dev/vda'
instance = db.instance_create(self.context, instance_ref)
conn.spawn(self.context, instance, None, [], None,
block_device_info=block_device_info)
self.assertFalse(self.cache_called_for_disk)
db.instance_destroy(self.context, instance['uuid'])
# Booted from volume but with placeholder image
instance_ref = self.test_instance
instance_ref['image_ref'] = 'my_fake_image'
instance_ref['root_device_name'] = '/dev/vda'
instance = db.instance_create(self.context, instance_ref)
conn.spawn(self.context, instance, None, [], None,
block_device_info=block_device_info)
self.assertFalse(self.cache_called_for_disk)
db.instance_destroy(self.context, instance['uuid'])
# Booted from an image
instance_ref['image_ref'] = 'my_fake_image'
instance = db.instance_create(self.context, instance_ref)
conn.spawn(self.context, instance, None, [], None)
self.assertTrue(self.cache_called_for_disk)
db.instance_destroy(self.context, instance['uuid'])
def test_create_image_plain(self):
gotFiles = []
def fake_image(self, instance, name, image_type=''):
class FakeImage(imagebackend.Image):
def __init__(self, instance, name):
self.path = os.path.join(instance['name'], name)
def create_image(self, prepare_template, base,
size, *args, **kwargs):
pass
def cache(self, fetch_func, filename, size=None,
*args, **kwargs):
gotFiles.append({'filename': filename,
'size': size})
def snapshot(self, name):
pass
return FakeImage(instance, name)
def fake_none(*args, **kwargs):
return
def fake_get_info(instance):
return {'state': power_state.RUNNING}
# Stop 'libvirt_driver._create_image' touching filesystem
self.stubs.Set(nova.virt.libvirt.imagebackend.Backend, "image",
fake_image)
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance = db.instance_create(self.context, instance_ref)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, 'to_xml', fake_none)
self.stubs.Set(conn, '_create_domain_and_network', fake_none)
self.stubs.Set(conn, 'get_info', fake_get_info)
image_meta = {'id': instance['image_ref']}
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance,
None,
image_meta)
conn._create_image(context, instance,
disk_info['mapping'])
xml = conn.to_xml(instance, None,
disk_info, image_meta)
wantFiles = [
{'filename': '356a192b7913b04c54574d18c28d46e6395428ab',
'size': 10 * 1024 * 1024 * 1024},
{'filename': 'ephemeral_20_default',
'size': 20 * 1024 * 1024 * 1024},
]
self.assertEquals(gotFiles, wantFiles)
def test_create_image_with_swap(self):
gotFiles = []
def fake_image(self, instance, name, image_type=''):
class FakeImage(imagebackend.Image):
def __init__(self, instance, name):
self.path = os.path.join(instance['name'], name)
def create_image(self, prepare_template, base,
size, *args, **kwargs):
pass
def cache(self, fetch_func, filename, size=None,
*args, **kwargs):
gotFiles.append({'filename': filename,
'size': size})
def snapshot(self, name):
pass
return FakeImage(instance, name)
def fake_none(*args, **kwargs):
return
def fake_get_info(instance):
return {'state': power_state.RUNNING}
# Stop 'libvirt_driver._create_image' touching filesystem
self.stubs.Set(nova.virt.libvirt.imagebackend.Backend, "image",
fake_image)
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
# Turn on some swap to exercise that codepath in _create_image
instance_ref['system_metadata']['instance_type_swap'] = 500
instance = db.instance_create(self.context, instance_ref)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, 'to_xml', fake_none)
self.stubs.Set(conn, '_create_domain_and_network', fake_none)
self.stubs.Set(conn, 'get_info', fake_get_info)
image_meta = {'id': instance['image_ref']}
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance,
None,
image_meta)
conn._create_image(context, instance,
disk_info['mapping'])
xml = conn.to_xml(instance, None,
disk_info, image_meta)
wantFiles = [
{'filename': '356a192b7913b04c54574d18c28d46e6395428ab',
'size': 10 * 1024 * 1024 * 1024},
{'filename': 'ephemeral_20_default',
'size': 20 * 1024 * 1024 * 1024},
{'filename': 'swap_500',
'size': 500 * 1024 * 1024},
]
self.assertEquals(gotFiles, wantFiles)
def test_get_console_output_file(self):
fake_libvirt_utils.files['console.log'] = '01234567890'
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance = db.instance_create(self.context, instance_ref)
console_dir = (os.path.join(tmpdir, instance['name']))
console_log = '%s/console.log' % (console_dir)
fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='file'>
<source path='%s'/>
<target port='0'/>
</console>
</devices>
</domain>
""" % console_log
def fake_lookup(id):
return FakeVirtDomain(fake_dom_xml)
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
try:
prev_max = libvirt_driver.MAX_CONSOLE_BYTES
libvirt_driver.MAX_CONSOLE_BYTES = 5
output = conn.get_console_output(instance)
finally:
libvirt_driver.MAX_CONSOLE_BYTES = prev_max
self.assertEquals('67890', output)
def test_get_console_output_pty(self):
fake_libvirt_utils.files['pty'] = '01234567890'
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance = db.instance_create(self.context, instance_ref)
console_dir = (os.path.join(tmpdir, instance['name']))
pty_file = '%s/fake_pty' % (console_dir)
fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='pty'>
<source path='%s'/>
<target port='0'/>
</console>
</devices>
</domain>
""" % pty_file
def fake_lookup(id):
return FakeVirtDomain(fake_dom_xml)
def _fake_flush(self, fake_pty):
return 'foo'
def _fake_append_to_file(self, data, fpath):
return 'pty'
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
libvirt_driver.LibvirtDriver._flush_libvirt_console = _fake_flush
libvirt_driver.LibvirtDriver._append_to_file = _fake_append_to_file
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
try:
prev_max = libvirt_driver.MAX_CONSOLE_BYTES
libvirt_driver.MAX_CONSOLE_BYTES = 5
output = conn.get_console_output(instance)
finally:
libvirt_driver.MAX_CONSOLE_BYTES = prev_max
self.assertEquals('67890', output)
def test_get_host_ip_addr(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ip = conn.get_host_ip_addr()
self.assertEquals(ip, CONF.my_ip)
def test_broken_connection(self):
for (error, domain) in (
(libvirt.VIR_ERR_SYSTEM_ERROR, libvirt.VIR_FROM_REMOTE),
(libvirt.VIR_ERR_SYSTEM_ERROR, libvirt.VIR_FROM_RPC),
(libvirt.VIR_ERR_INTERNAL_ERROR, libvirt.VIR_FROM_RPC)):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_wrapped_conn")
self.mox.StubOutWithMock(conn._wrapped_conn, "getLibVersion")
self.mox.StubOutWithMock(libvirt.libvirtError, "get_error_code")
self.mox.StubOutWithMock(libvirt.libvirtError, "get_error_domain")
conn._wrapped_conn.getLibVersion().AndRaise(
libvirt.libvirtError("fake failure"))
libvirt.libvirtError.get_error_code().AndReturn(error)
libvirt.libvirtError.get_error_domain().AndReturn(domain)
self.mox.ReplayAll()
self.assertFalse(conn._test_connection())
self.mox.UnsetStubs()
def test_immediate_delete(self):
def fake_lookup_by_name(instance_name):
raise exception.InstanceNotFound(instance_id=instance_name)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
instance = db.instance_create(self.context, self.test_instance)
conn.destroy(instance, {})
def test_destroy_removes_disk(self):
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver,
'_undefine_domain')
libvirt_driver.LibvirtDriver._undefine_domain(instance)
self.mox.StubOutWithMock(shutil, "rmtree")
shutil.rmtree(os.path.join(CONF.instances_path, instance['name']))
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_cleanup_lvm')
libvirt_driver.LibvirtDriver._cleanup_lvm(instance)
# Start test
self.mox.ReplayAll()
def fake_destroy(instance):
pass
def fake_os_path_exists(path):
return True
def fake_unplug_vifs(instance, network_info):
pass
def fake_unfilter_instance(instance, network_info):
pass
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_destroy', fake_destroy)
self.stubs.Set(conn, 'unplug_vifs', fake_unplug_vifs)
self.stubs.Set(conn.firewall_driver,
'unfilter_instance', fake_unfilter_instance)
self.stubs.Set(os.path, 'exists', fake_os_path_exists)
conn.destroy(instance, [])
def test_destroy_not_removes_disk(self):
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver,
'_undefine_domain')
libvirt_driver.LibvirtDriver._undefine_domain(instance)
# Start test
self.mox.ReplayAll()
def fake_destroy(instance):
pass
def fake_os_path_exists(path):
return True
def fake_unplug_vifs(instance, network_info):
pass
def fake_unfilter_instance(instance, network_info):
pass
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_destroy', fake_destroy)
self.stubs.Set(conn, 'unplug_vifs', fake_unplug_vifs)
self.stubs.Set(conn.firewall_driver,
'unfilter_instance', fake_unfilter_instance)
self.stubs.Set(os.path, 'exists', fake_os_path_exists)
conn.destroy(instance, [], None, False)
def test_destroy_undefines(self):
mock = self.mox.CreateMock(libvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndReturn(1)
self.mox.ReplayAll()
def fake_lookup_by_name(instance_name):
return mock
def fake_get_info(instance_name):
return {'state': power_state.SHUTDOWN, 'id': -1}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
self.stubs.Set(conn, 'get_info', fake_get_info)
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
conn.destroy(instance, [])
def test_destroy_undefines_no_undefine_flags(self):
mock = self.mox.CreateMock(libvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(libvirt.libvirtError('Err'))
mock.undefine()
self.mox.ReplayAll()
def fake_lookup_by_name(instance_name):
return mock
def fake_get_info(instance_name):
return {'state': power_state.SHUTDOWN, 'id': -1}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
self.stubs.Set(conn, 'get_info', fake_get_info)
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
conn.destroy(instance, [])
def test_destroy_undefines_no_attribute_with_managed_save(self):
mock = self.mox.CreateMock(libvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(AttributeError())
mock.hasManagedSaveImage(0).AndReturn(True)
mock.managedSaveRemove(0)
mock.undefine()
self.mox.ReplayAll()
def fake_lookup_by_name(instance_name):
return mock
def fake_get_info(instance_name):
return {'state': power_state.SHUTDOWN, 'id': -1}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
self.stubs.Set(conn, 'get_info', fake_get_info)
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
conn.destroy(instance, [])
def test_destroy_undefines_no_attribute_no_managed_save(self):
mock = self.mox.CreateMock(libvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(AttributeError())
mock.hasManagedSaveImage(0).AndRaise(AttributeError())
mock.undefine()
self.mox.ReplayAll()
def fake_lookup_by_name(instance_name):
return mock
def fake_get_info(instance_name):
return {'state': power_state.SHUTDOWN, 'id': -1}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
self.stubs.Set(conn, 'get_info', fake_get_info)
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
conn.destroy(instance, [])
def test_private_destroy_not_found(self):
mock = self.mox.CreateMock(libvirt.virDomain)
mock.ID()
mock.destroy()
self.mox.ReplayAll()
def fake_lookup_by_name(instance_name):
return mock
def fake_get_info(instance_name):
raise exception.InstanceNotFound(instance_id=instance_name)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
self.stubs.Set(conn, 'get_info', fake_get_info)
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
# NOTE(vish): verifies destroy doesn't raise if the instance disappears
conn._destroy(instance)
def test_disk_over_committed_size_total(self):
# Ensure destroy calls managedSaveRemove for saved instance.
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
def list_instances():
return ['fake1', 'fake2']
self.stubs.Set(conn, 'list_instances', list_instances)
fake_disks = {'fake1': [{'type': 'qcow2', 'path': '/somepath/disk1',
'virt_disk_size': '10737418240',
'backing_file': '/somepath/disk1',
'disk_size': '83886080',
'over_committed_disk_size': '10653532160'}],
'fake2': [{'type': 'raw', 'path': '/somepath/disk2',
'virt_disk_size': '0',
'backing_file': '/somepath/disk2',
'disk_size': '10737418240',
'over_committed_disk_size': '0'}]}
def get_info(instance_name):
return jsonutils.dumps(fake_disks.get(instance_name))
self.stubs.Set(conn, 'get_instance_disk_info', get_info)
result = conn.get_disk_over_committed_size_total()
self.assertEqual(result, 10653532160)
def test_cpu_info(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigCPU()
cpu.model = "Opteron_G4"
cpu.vendor = "AMD"
cpu.arch = "x86_64"
cpu.cores = 2
cpu.threads = 1
cpu.sockets = 4
cpu.add_feature(vconfig.LibvirtConfigCPUFeature("extapic"))
cpu.add_feature(vconfig.LibvirtConfigCPUFeature("3dnow"))
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
guest = vconfig.LibvirtConfigGuest()
guest.ostype = vm_mode.HVM
guest.arch = "x86_64"
guest.domtype = ["kvm"]
caps.guests.append(guest)
guest = vconfig.LibvirtConfigGuest()
guest.ostype = vm_mode.HVM
guest.arch = "i686"
guest.domtype = ["kvm"]
caps.guests.append(guest)
return caps
self.stubs.Set(libvirt_driver.LibvirtDriver,
'get_host_capabilities',
get_host_capabilities_stub)
want = {"vendor": "AMD",
"features": ["extapic", "3dnow"],
"model": "Opteron_G4",
"arch": "x86_64",
"topology": {"cores": 2, "threads": 1, "sockets": 4}}
got = jsonutils.loads(conn.get_cpu_info())
self.assertEqual(want, got)
def test_diagnostic_vcpus_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
raise libvirt.libvirtError('vcpus missing')
def blockStats(self, path):
return (169L, 688640L, 0L, 0L, -1L)
def interfaceStats(self, path):
return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
def memoryStats(self):
return {'actual': 220160L, 'rss': 200164L}
def maxMemory(self):
return 280160L
def fake_lookup_name(name):
return DiagFakeDomain()
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actual = conn.get_diagnostics({"name": "testvirt"})
expect = {'vda_read': 688640L,
'vda_read_req': 169L,
'vda_write': 0L,
'vda_write_req': 0L,
'vda_errors': -1L,
'vdb_read': 688640L,
'vdb_read_req': 169L,
'vdb_write': 0L,
'vdb_write_req': 0L,
'vdb_errors': -1L,
'memory': 280160L,
'memory-actual': 220160L,
'memory-rss': 200164L,
'vnet0_rx': 4408L,
'vnet0_rx_drop': 0L,
'vnet0_rx_errors': 0L,
'vnet0_rx_packets': 82L,
'vnet0_tx': 0L,
'vnet0_tx_drop': 0L,
'vnet0_tx_errors': 0L,
'vnet0_tx_packets': 0L,
}
self.assertEqual(actual, expect)
def test_diagnostic_blockstats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000L, 0),
(1, 1, 1640000000L, 0),
(2, 1, 3040000000L, 0),
(3, 1, 1420000000L, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
raise libvirt.libvirtError('blockStats missing')
def interfaceStats(self, path):
return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
def memoryStats(self):
return {'actual': 220160L, 'rss': 200164L}
def maxMemory(self):
return 280160L
def fake_lookup_name(name):
return DiagFakeDomain()
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actual = conn.get_diagnostics({"name": "testvirt"})
expect = {'cpu0_time': 15340000000L,
'cpu1_time': 1640000000L,
'cpu2_time': 3040000000L,
'cpu3_time': 1420000000L,
'memory': 280160L,
'memory-actual': 220160L,
'memory-rss': 200164L,
'vnet0_rx': 4408L,
'vnet0_rx_drop': 0L,
'vnet0_rx_errors': 0L,
'vnet0_rx_packets': 82L,
'vnet0_tx': 0L,
'vnet0_tx_drop': 0L,
'vnet0_tx_errors': 0L,
'vnet0_tx_packets': 0L,
}
self.assertEqual(actual, expect)
def test_diagnostic_interfacestats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000L, 0),
(1, 1, 1640000000L, 0),
(2, 1, 3040000000L, 0),
(3, 1, 1420000000L, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169L, 688640L, 0L, 0L, -1L)
def interfaceStats(self, path):
raise libvirt.libvirtError('interfaceStat missing')
def memoryStats(self):
return {'actual': 220160L, 'rss': 200164L}
def maxMemory(self):
return 280160L
def fake_lookup_name(name):
return DiagFakeDomain()
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actual = conn.get_diagnostics({"name": "testvirt"})
expect = {'cpu0_time': 15340000000L,
'cpu1_time': 1640000000L,
'cpu2_time': 3040000000L,
'cpu3_time': 1420000000L,
'vda_read': 688640L,
'vda_read_req': 169L,
'vda_write': 0L,
'vda_write_req': 0L,
'vda_errors': -1L,
'vdb_read': 688640L,
'vdb_read_req': 169L,
'vdb_write': 0L,
'vdb_write_req': 0L,
'vdb_errors': -1L,
'memory': 280160L,
'memory-actual': 220160L,
'memory-rss': 200164L,
}
self.assertEqual(actual, expect)
def test_diagnostic_memorystats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000L, 0),
(1, 1, 1640000000L, 0),
(2, 1, 3040000000L, 0),
(3, 1, 1420000000L, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169L, 688640L, 0L, 0L, -1L)
def interfaceStats(self, path):
return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
def memoryStats(self):
raise libvirt.libvirtError('memoryStats missing')
def maxMemory(self):
return 280160L
def fake_lookup_name(name):
return DiagFakeDomain()
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actual = conn.get_diagnostics({"name": "testvirt"})
expect = {'cpu0_time': 15340000000L,
'cpu1_time': 1640000000L,
'cpu2_time': 3040000000L,
'cpu3_time': 1420000000L,
'vda_read': 688640L,
'vda_read_req': 169L,
'vda_write': 0L,
'vda_write_req': 0L,
'vda_errors': -1L,
'vdb_read': 688640L,
'vdb_read_req': 169L,
'vdb_write': 0L,
'vdb_write_req': 0L,
'vdb_errors': -1L,
'memory': 280160L,
'vnet0_rx': 4408L,
'vnet0_rx_drop': 0L,
'vnet0_rx_errors': 0L,
'vnet0_rx_packets': 82L,
'vnet0_tx': 0L,
'vnet0_tx_drop': 0L,
'vnet0_tx_errors': 0L,
'vnet0_tx_packets': 0L,
}
self.assertEqual(actual, expect)
def test_diagnostic_full(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000L, 0),
(1, 1, 1640000000L, 0),
(2, 1, 3040000000L, 0),
(3, 1, 1420000000L, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169L, 688640L, 0L, 0L, -1L)
def interfaceStats(self, path):
return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
def memoryStats(self):
return {'actual': 220160L, 'rss': 200164L}
def maxMemory(self):
return 280160L
def fake_lookup_name(name):
return DiagFakeDomain()
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actual = conn.get_diagnostics({"name": "testvirt"})
expect = {'cpu0_time': 15340000000L,
'cpu1_time': 1640000000L,
'cpu2_time': 3040000000L,
'cpu3_time': 1420000000L,
'vda_read': 688640L,
'vda_read_req': 169L,
'vda_write': 0L,
'vda_write_req': 0L,
'vda_errors': -1L,
'vdb_read': 688640L,
'vdb_read_req': 169L,
'vdb_write': 0L,
'vdb_write_req': 0L,
'vdb_errors': -1L,
'memory': 280160L,
'memory-actual': 220160L,
'memory-rss': 200164L,
'vnet0_rx': 4408L,
'vnet0_rx_drop': 0L,
'vnet0_rx_errors': 0L,
'vnet0_rx_packets': 82L,
'vnet0_tx': 0L,
'vnet0_tx_drop': 0L,
'vnet0_tx_errors': 0L,
'vnet0_tx_packets': 0L,
}
self.assertEqual(actual, expect)
def test_failing_vcpu_count(self):
"""Domain can fail to return the vcpu description in case it's
just starting up or shutting down. Make sure None is handled
gracefully.
"""
class DiagFakeDomain(object):
def __init__(self, vcpus):
self._vcpus = vcpus
def vcpus(self):
if self._vcpus is None:
return None
else:
return ([1] * self._vcpus, [True] * self._vcpus)
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conn = driver._conn
self.mox.StubOutWithMock(driver, 'list_instance_ids')
conn.lookupByID = self.mox.CreateMockAnything()
driver.list_instance_ids().AndReturn([1, 2])
conn.lookupByID(1).AndReturn(DiagFakeDomain(None))
conn.lookupByID(2).AndReturn(DiagFakeDomain(5))
self.mox.ReplayAll()
self.assertEqual(5, driver.get_vcpu_used())
def test_get_instance_capabilities(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
def get_host_capabilities_stub(self):
caps = vconfig.LibvirtConfigCaps()
guest = vconfig.LibvirtConfigGuest()
guest.ostype = 'hvm'
guest.arch = 'x86_64'
guest.domtype = ['kvm', 'qemu']
caps.guests.append(guest)
guest = vconfig.LibvirtConfigGuest()
guest.ostype = 'hvm'
guest.arch = 'i686'
guest.domtype = ['kvm']
caps.guests.append(guest)
return caps
self.stubs.Set(libvirt_driver.LibvirtDriver,
'get_host_capabilities',
get_host_capabilities_stub)
want = [('x86_64', 'kvm', 'hvm'),
('x86_64', 'qemu', 'hvm'),
('i686', 'kvm', 'hvm')]
got = conn.get_instance_capabilities()
self.assertEqual(want, got)
def test_event_dispatch(self):
# Validate that the libvirt self-pipe for forwarding
# events between threads is working sanely
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
got_events = []
def handler(event):
got_events.append(event)
conn.register_event_listener(handler)
conn._init_events_pipe()
event1 = virtevent.LifecycleEvent(
"cef19ce0-0ca2-11df-855d-b19fbce37686",
virtevent.EVENT_LIFECYCLE_STARTED)
event2 = virtevent.LifecycleEvent(
"cef19ce0-0ca2-11df-855d-b19fbce37686",
virtevent.EVENT_LIFECYCLE_PAUSED)
conn._queue_event(event1)
conn._queue_event(event2)
conn._dispatch_events()
want_events = [event1, event2]
self.assertEqual(want_events, got_events)
event3 = virtevent.LifecycleEvent(
"cef19ce0-0ca2-11df-855d-b19fbce37686",
virtevent.EVENT_LIFECYCLE_RESUMED)
event4 = virtevent.LifecycleEvent(
"cef19ce0-0ca2-11df-855d-b19fbce37686",
virtevent.EVENT_LIFECYCLE_STOPPED)
conn._queue_event(event3)
conn._queue_event(event4)
conn._dispatch_events()
want_events = [event1, event2, event3, event4]
self.assertEqual(want_events, got_events)
def test_event_lifecycle(self):
# Validate that libvirt events are correctly translated
# to Nova events
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
got_events = []
def handler(event):
got_events.append(event)
conn.register_event_listener(handler)
conn._init_events_pipe()
fake_dom_xml = """
<domain type='kvm'>
<uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
</devices>
</domain>
"""
dom = FakeVirtDomain(fake_dom_xml,
"cef19ce0-0ca2-11df-855d-b19fbce37686")
conn._event_lifecycle_callback(conn._conn,
dom,
libvirt.VIR_DOMAIN_EVENT_STOPPED,
0,
conn)
conn._dispatch_events()
self.assertEqual(len(got_events), 1)
self.assertEqual(type(got_events[0]), virtevent.LifecycleEvent)
self.assertEqual(got_events[0].uuid,
"cef19ce0-0ca2-11df-855d-b19fbce37686")
self.assertEqual(got_events[0].transition,
virtevent.EVENT_LIFECYCLE_STOPPED)
def test_set_cache_mode(self):
self.flags(disk_cachemodes=['file=directsync'])
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuestDisk()
fake_conf.source_type = 'file'
conn.set_cache_mode(fake_conf)
self.assertEqual(fake_conf.driver_cache, 'directsync')
def test_set_cache_mode_invalid_mode(self):
self.flags(disk_cachemodes=['file=FAKE'])
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuestDisk()
fake_conf.source_type = 'file'
conn.set_cache_mode(fake_conf)
self.assertEqual(fake_conf.driver_cache, None)
def test_set_cache_mode_invalid_object(self):
self.flags(disk_cachemodes=['file=directsync'])
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuest()
fake_conf.driver_cache = 'fake'
conn.set_cache_mode(fake_conf)
self.assertEqual(fake_conf.driver_cache, 'fake')
def _test_shared_storage_detection(self, is_same):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.mox.StubOutWithMock(conn, 'get_host_ip_addr')
self.mox.StubOutWithMock(utils, 'execute')
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(os, 'unlink')
conn.get_host_ip_addr().AndReturn('bar')
utils.execute('ssh', 'foo', 'touch', mox.IgnoreArg())
os.path.exists(mox.IgnoreArg()).AndReturn(is_same)
if is_same:
os.unlink(mox.IgnoreArg())
else:
utils.execute('ssh', 'foo', 'rm', mox.IgnoreArg())
self.mox.ReplayAll()
return conn._is_storage_shared_with('foo', '/path')
def test_shared_storage_detection_same_host(self):
self.assertTrue(self._test_shared_storage_detection(True))
def test_shared_storage_detection_different_host(self):
self.assertFalse(self._test_shared_storage_detection(False))
def test_shared_storage_detection_easy(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.mox.StubOutWithMock(conn, 'get_host_ip_addr')
self.mox.StubOutWithMock(utils, 'execute')
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(os, 'unlink')
conn.get_host_ip_addr().AndReturn('foo')
self.mox.ReplayAll()
self.assertTrue(conn._is_storage_shared_with('foo', '/path'))
class HostStateTestCase(test.TestCase):
cpu_info = ('{"vendor": "Intel", "model": "pentium", "arch": "i686", '
'"features": ["ssse3", "monitor", "pni", "sse2", "sse", '
'"fxsr", "clflush", "pse36", "pat", "cmov", "mca", "pge", '
'"mtrr", "sep", "apic"], '
'"topology": {"cores": "1", "threads": "1", "sockets": "1"}}')
instance_caps = [("x86_64", "kvm", "hvm"), ("i686", "kvm", "hvm")]
class FakeConnection(object):
"""Fake connection object."""
def get_vcpu_total(self):
return 1
def get_vcpu_used(self):
return 0
def get_cpu_info(self):
return HostStateTestCase.cpu_info
def get_local_gb_info(self):
return {'total': 100, 'used': 20, 'free': 80}
def get_memory_mb_total(self):
return 497
def get_memory_mb_used(self):
return 88
def get_hypervisor_type(self):
return 'QEMU'
def get_hypervisor_version(self):
return 13091
def get_hypervisor_hostname(self):
return 'compute1'
def get_host_uptime(self):
return ('10:01:16 up 1:36, 6 users, '
'load average: 0.21, 0.16, 0.19')
def get_disk_available_least(self):
return 13091
def get_instance_capabilities(self):
return HostStateTestCase.instance_caps
def test_update_status(self):
hs = libvirt_driver.HostState(self.FakeConnection())
stats = hs._stats
self.assertEquals(stats["vcpus"], 1)
self.assertEquals(stats["vcpus_used"], 0)
self.assertEquals(stats["cpu_info"],
{"vendor": "Intel", "model": "pentium", "arch": "i686",
"features": ["ssse3", "monitor", "pni", "sse2", "sse",
"fxsr", "clflush", "pse36", "pat", "cmov",
"mca", "pge", "mtrr", "sep", "apic"],
"topology": {"cores": "1", "threads": "1", "sockets": "1"}
})
self.assertEquals(stats["disk_total"], 100)
self.assertEquals(stats["disk_used"], 20)
self.assertEquals(stats["disk_available"], 80)
self.assertEquals(stats["host_memory_total"], 497)
self.assertEquals(stats["host_memory_free"], 409)
self.assertEquals(stats["hypervisor_type"], 'QEMU')
self.assertEquals(stats["hypervisor_version"], 13091)
self.assertEquals(stats["hypervisor_hostname"], 'compute1')
class NWFilterFakes:
def __init__(self):
self.filters = {}
def nwfilterLookupByName(self, name):
if name in self.filters:
return self.filters[name]
raise libvirt.libvirtError('Filter Not Found')
def filterDefineXMLMock(self, xml):
class FakeNWFilterInternal:
def __init__(self, parent, name, xml):
self.name = name
self.parent = parent
self.xml = xml
def undefine(self):
del self.parent.filters[self.name]
pass
tree = etree.fromstring(xml)
name = tree.get('name')
if name not in self.filters:
self.filters[name] = FakeNWFilterInternal(self, name, xml)
return True
class IptablesFirewallTestCase(test.TestCase):
def setUp(self):
super(IptablesFirewallTestCase, self).setUp()
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.RequestContext(self.user_id, self.project_id)
class FakeLibvirtDriver(object):
def nwfilterDefineXML(*args, **kwargs):
"""setup_basic_rules in nwfilter calls this."""
pass
self.fake_libvirt_connection = FakeLibvirtDriver()
self.fw = firewall.IptablesFirewallDriver(
fake.FakeVirtAPI(),
get_connection=lambda: self.fake_libvirt_connection)
in_rules = [
'# Generated by iptables-save v1.4.10 on Sat Feb 19 00:03:19 2011',
'*nat',
':PREROUTING ACCEPT [1170:189210]',
':INPUT ACCEPT [844:71028]',
':OUTPUT ACCEPT [5149:405186]',
':POSTROUTING ACCEPT [5063:386098]',
'# Completed on Tue Dec 18 15:50:25 2012',
'# Generated by iptables-save v1.4.12 on Tue Dec 18 15:50:25 201;',
'*mangle',
':PREROUTING ACCEPT [241:39722]',
':INPUT ACCEPT [230:39282]',
':FORWARD ACCEPT [0:0]',
':OUTPUT ACCEPT [266:26558]',
':POSTROUTING ACCEPT [267:26590]',
'-A POSTROUTING -o virbr0 -p udp -m udp --dport 68 -j CHECKSUM '
'--checksum-fill',
'COMMIT',
'# Completed on Tue Dec 18 15:50:25 2012',
'# Generated by iptables-save v1.4.4 on Mon Dec 6 11:54:13 2010',
'*filter',
':INPUT ACCEPT [969615:281627771]',
':FORWARD ACCEPT [0:0]',
':OUTPUT ACCEPT [915599:63811649]',
':nova-block-ipv4 - [0:0]',
'[0:0] -A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT ',
'[0:0] -A FORWARD -d 192.168.122.0/24 -o virbr0 -m state --state RELATED'
',ESTABLISHED -j ACCEPT ',
'[0:0] -A FORWARD -s 192.168.122.0/24 -i virbr0 -j ACCEPT ',
'[0:0] -A FORWARD -i virbr0 -o virbr0 -j ACCEPT ',
'[0:0] -A FORWARD -o virbr0 -j REJECT '
'--reject-with icmp-port-unreachable ',
'[0:0] -A FORWARD -i virbr0 -j REJECT '
'--reject-with icmp-port-unreachable ',
'COMMIT',
'# Completed on Mon Dec 6 11:54:13 2010',
]
in6_filter_rules = [
'# Generated by ip6tables-save v1.4.4 on Tue Jan 18 23:47:56 2011',
'*filter',
':INPUT ACCEPT [349155:75810423]',
':FORWARD ACCEPT [0:0]',
':OUTPUT ACCEPT [349256:75777230]',
'COMMIT',
'# Completed on Tue Jan 18 23:47:56 2011',
]
def _create_instance_ref(self):
return db.instance_create(self.context,
{'user_id': 'fake',
'project_id': 'fake',
'instance_type_id': 1})
def test_static_filters(self):
instance_ref = self._create_instance_ref()
src_instance_ref = self._create_instance_ref()
admin_ctxt = context.get_admin_context()
secgroup = db.security_group_create(admin_ctxt,
{'user_id': 'fake',
'project_id': 'fake',
'name': 'testgroup',
'description': 'test group'})
src_secgroup = db.security_group_create(admin_ctxt,
{'user_id': 'fake',
'project_id': 'fake',
'name': 'testsourcegroup',
'description': 'src group'})
db.security_group_rule_create(admin_ctxt,
{'parent_group_id': secgroup['id'],
'protocol': 'icmp',
'from_port': -1,
'to_port': -1,
'cidr': '192.168.11.0/24'})
db.security_group_rule_create(admin_ctxt,
{'parent_group_id': secgroup['id'],
'protocol': 'icmp',
'from_port': 8,
'to_port': -1,
'cidr': '192.168.11.0/24'})
db.security_group_rule_create(admin_ctxt,
{'parent_group_id': secgroup['id'],
'protocol': 'tcp',
'from_port': 80,
'to_port': 81,
'cidr': '192.168.10.0/24'})
db.security_group_rule_create(admin_ctxt,
{'parent_group_id': secgroup['id'],
'protocol': 'tcp',
'from_port': 80,
'to_port': 81,
'group_id': src_secgroup['id']})
db.security_group_rule_create(admin_ctxt,
{'parent_group_id': secgroup['id'],
'group_id': src_secgroup['id']})
db.instance_add_security_group(admin_ctxt, instance_ref['uuid'],
secgroup['id'])
db.instance_add_security_group(admin_ctxt, src_instance_ref['uuid'],
src_secgroup['id'])
instance_ref = db.instance_get(admin_ctxt, instance_ref['id'])
src_instance_ref = db.instance_get(admin_ctxt, src_instance_ref['id'])
# self.fw.add_instance(instance_ref)
def fake_iptables_execute(*cmd, **kwargs):
process_input = kwargs.get('process_input', None)
if cmd == ('ip6tables-save', '-c'):
return '\n'.join(self.in6_filter_rules), None
if cmd == ('iptables-save', '-c'):
return '\n'.join(self.in_rules), None
if cmd == ('iptables-restore', '-c'):
lines = process_input.split('\n')
if '*filter' in lines:
self.out_rules = lines
return '', ''
if cmd == ('ip6tables-restore', '-c',):
lines = process_input.split('\n')
if '*filter' in lines:
self.out6_rules = lines
return '', ''
network_model = _fake_network_info(self.stubs, 1, spectacular=True)
from nova.network import linux_net
linux_net.iptables_manager.execute = fake_iptables_execute
_fake_stub_out_get_nw_info(self.stubs, lambda *a, **kw: network_model)
network_info = network_model.legacy()
self.fw.prepare_instance_filter(instance_ref, network_info)
self.fw.apply_instance_filter(instance_ref, network_info)
in_rules = filter(lambda l: not l.startswith('#'),
self.in_rules)
for rule in in_rules:
if 'nova' not in rule:
self.assertTrue(rule in self.out_rules,
'Rule went missing: %s' % rule)
instance_chain = None
for rule in self.out_rules:
# This is pretty crude, but it'll do for now
# last two octets change
if re.search('-d 192.168.[0-9]{1,3}.[0-9]{1,3} -j', rule):
instance_chain = rule.split(' ')[-1]
break
self.assertTrue(instance_chain, "The instance chain wasn't added")
security_group_chain = None
for rule in self.out_rules:
# This is pretty crude, but it'll do for now
if '-A %s -j' % instance_chain in rule:
security_group_chain = rule.split(' ')[-1]
break
self.assertTrue(security_group_chain,
"The security group chain wasn't added")
regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p icmp '
'-s 192.168.11.0/24')
self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
"ICMP acceptance rule wasn't added")
regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p icmp -m icmp '
'--icmp-type 8 -s 192.168.11.0/24')
self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
"ICMP Echo Request acceptance rule wasn't added")
for ip in network_model.fixed_ips():
if ip['version'] != 4:
continue
regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p tcp -m multiport '
'--dports 80:81 -s %s' % ip['address'])
self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
"TCP port 80/81 acceptance rule wasn't added")
regex = re.compile('\[0\:0\] -A .* -j ACCEPT -s '
'%s' % ip['address'])
self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
"Protocol/port-less acceptance rule wasn't added")
regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p tcp '
'-m multiport --dports 80:81 -s 192.168.10.0/24')
self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
"TCP port 80/81 acceptance rule wasn't added")
db.instance_destroy(admin_ctxt, instance_ref['uuid'])
def test_filters_for_instance_with_ip_v6(self):
self.flags(use_ipv6=True)
network_info = _fake_network_info(self.stubs, 1)
rulesv4, rulesv6 = self.fw._filters_for_instance("fake", network_info)
self.assertEquals(len(rulesv4), 2)
self.assertEquals(len(rulesv6), 1)
def test_filters_for_instance_without_ip_v6(self):
self.flags(use_ipv6=False)
network_info = _fake_network_info(self.stubs, 1)
rulesv4, rulesv6 = self.fw._filters_for_instance("fake", network_info)
self.assertEquals(len(rulesv4), 2)
self.assertEquals(len(rulesv6), 0)
def test_multinic_iptables(self):
ipv4_rules_per_addr = 1
ipv4_addr_per_network = 2
ipv6_rules_per_addr = 1
ipv6_addr_per_network = 1
networks_count = 5
instance_ref = self._create_instance_ref()
network_info = _fake_network_info(self.stubs, networks_count,
ipv4_addr_per_network)
ipv4_len = len(self.fw.iptables.ipv4['filter'].rules)
ipv6_len = len(self.fw.iptables.ipv6['filter'].rules)
inst_ipv4, inst_ipv6 = self.fw.instance_rules(instance_ref,
network_info)
self.fw.prepare_instance_filter(instance_ref, network_info)
ipv4 = self.fw.iptables.ipv4['filter'].rules
ipv6 = self.fw.iptables.ipv6['filter'].rules
ipv4_network_rules = len(ipv4) - len(inst_ipv4) - ipv4_len
ipv6_network_rules = len(ipv6) - len(inst_ipv6) - ipv6_len
# Extra rules are for the DHCP request
rules = (ipv4_rules_per_addr * ipv4_addr_per_network *
networks_count) + 2
self.assertEquals(ipv4_network_rules, rules)
self.assertEquals(ipv6_network_rules,
ipv6_rules_per_addr * ipv6_addr_per_network * networks_count)
def test_do_refresh_security_group_rules(self):
instance_ref = self._create_instance_ref()
self.mox.StubOutWithMock(self.fw,
'instance_rules')
self.mox.StubOutWithMock(self.fw,
'add_filters_for_instance',
use_mock_anything=True)
self.fw.instance_rules(instance_ref,
mox.IgnoreArg()).AndReturn((None, None))
self.fw.add_filters_for_instance(instance_ref, mox.IgnoreArg(),
mox.IgnoreArg())
self.fw.instance_rules(instance_ref,
mox.IgnoreArg()).AndReturn((None, None))
self.fw.add_filters_for_instance(instance_ref, mox.IgnoreArg(),
mox.IgnoreArg())
self.mox.ReplayAll()
self.fw.prepare_instance_filter(instance_ref, mox.IgnoreArg())
self.fw.instances[instance_ref['id']] = instance_ref
self.fw.do_refresh_security_group_rules("fake")
def test_unfilter_instance_undefines_nwfilter(self):
admin_ctxt = context.get_admin_context()
fakefilter = NWFilterFakes()
_xml_mock = fakefilter.filterDefineXMLMock
self.fw.nwfilter._conn.nwfilterDefineXML = _xml_mock
_lookup_name = fakefilter.nwfilterLookupByName
self.fw.nwfilter._conn.nwfilterLookupByName = _lookup_name
instance_ref = self._create_instance_ref()
network_info = _fake_network_info(self.stubs, 1)
self.fw.setup_basic_filtering(instance_ref, network_info)
self.fw.prepare_instance_filter(instance_ref, network_info)
self.fw.apply_instance_filter(instance_ref, network_info)
original_filter_count = len(fakefilter.filters)
self.fw.unfilter_instance(instance_ref, network_info)
# should undefine just the instance filter
self.assertEqual(original_filter_count - len(fakefilter.filters), 1)
db.instance_destroy(admin_ctxt, instance_ref['uuid'])
def test_provider_firewall_rules(self):
# setup basic instance data
instance_ref = self._create_instance_ref()
# FRAGILE: peeks at how the firewall names chains
chain_name = 'inst-%s' % instance_ref['id']
# create a firewall via setup_basic_filtering like libvirt_conn.spawn
# should have a chain with 0 rules
network_info = _fake_network_info(self.stubs, 1)
self.fw.setup_basic_filtering(instance_ref, network_info)
self.assertTrue('provider' in self.fw.iptables.ipv4['filter'].chains)
rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules
if rule.chain == 'provider']
self.assertEqual(0, len(rules))
admin_ctxt = context.get_admin_context()
# add a rule and send the update message, check for 1 rule
provider_fw0 = db.provider_fw_rule_create(admin_ctxt,
{'protocol': 'tcp',
'cidr': '10.99.99.99/32',
'from_port': 1,
'to_port': 65535})
self.fw.refresh_provider_fw_rules()
rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules
if rule.chain == 'provider']
self.assertEqual(1, len(rules))
# Add another, refresh, and make sure number of rules goes to two
provider_fw1 = db.provider_fw_rule_create(admin_ctxt,
{'protocol': 'udp',
'cidr': '10.99.99.99/32',
'from_port': 1,
'to_port': 65535})
self.fw.refresh_provider_fw_rules()
rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules
if rule.chain == 'provider']
self.assertEqual(2, len(rules))
# create the instance filter and make sure it has a jump rule
self.fw.prepare_instance_filter(instance_ref, network_info)
self.fw.apply_instance_filter(instance_ref, network_info)
inst_rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules
if rule.chain == chain_name]
jump_rules = [rule for rule in inst_rules if '-j' in rule.rule]
provjump_rules = []
# IptablesTable doesn't make rules unique internally
for rule in jump_rules:
if 'provider' in rule.rule and rule not in provjump_rules:
provjump_rules.append(rule)
self.assertEqual(1, len(provjump_rules))
# remove a rule from the db, cast to compute to refresh rule
db.provider_fw_rule_destroy(admin_ctxt, provider_fw1['id'])
self.fw.refresh_provider_fw_rules()
rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules
if rule.chain == 'provider']
self.assertEqual(1, len(rules))
class NWFilterTestCase(test.TestCase):
def setUp(self):
super(NWFilterTestCase, self).setUp()
class Mock(object):
pass
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.RequestContext(self.user_id, self.project_id)
self.fake_libvirt_connection = Mock()
self.fw = firewall.NWFilterFirewall(fake.FakeVirtAPI(),
lambda: self.fake_libvirt_connection)
def test_cidr_rule_nwfilter_xml(self):
cloud_controller = cloud.CloudController()
cloud_controller.create_security_group(self.context,
'testgroup',
'test group description')
cloud_controller.authorize_security_group_ingress(self.context,
'testgroup',
from_port='80',
to_port='81',
ip_protocol='tcp',
cidr_ip='0.0.0.0/0')
security_group = db.security_group_get_by_name(self.context,
'fake',
'testgroup')
self.teardown_security_group()
def teardown_security_group(self):
cloud_controller = cloud.CloudController()
cloud_controller.delete_security_group(self.context, 'testgroup')
def setup_and_return_security_group(self):
cloud_controller = cloud.CloudController()
cloud_controller.create_security_group(self.context,
'testgroup',
'test group description')
cloud_controller.authorize_security_group_ingress(self.context,
'testgroup',
from_port='80',
to_port='81',
ip_protocol='tcp',
cidr_ip='0.0.0.0/0')
return db.security_group_get_by_name(self.context, 'fake', 'testgroup')
def _create_instance(self):
return db.instance_create(self.context,
{'user_id': 'fake',
'project_id': 'fake',
'instance_type_id': 1})
def _create_instance_type(self, params=None):
"""Create a test instance."""
if not params:
params = {}
context = self.context.elevated()
inst = {}
inst['name'] = 'm1.small'
inst['memory_mb'] = '1024'
inst['vcpus'] = '1'
inst['root_gb'] = '10'
inst['ephemeral_gb'] = '20'
inst['flavorid'] = '1'
inst['swap'] = '2048'
inst['rxtx_factor'] = 1
inst.update(params)
return db.instance_type_create(context, inst)['id']
def test_creates_base_rule_first(self):
# These come pre-defined by libvirt
self.defined_filters = ['no-mac-spoofing',
'no-ip-spoofing',
'no-arp-spoofing',
'allow-dhcp-server']
self.recursive_depends = {}
for f in self.defined_filters:
self.recursive_depends[f] = []
def _filterDefineXMLMock(xml):
dom = minidom.parseString(xml)
name = dom.firstChild.getAttribute('name')
self.recursive_depends[name] = []
for f in dom.getElementsByTagName('filterref'):
ref = f.getAttribute('filter')
self.assertTrue(ref in self.defined_filters,
('%s referenced filter that does ' +
'not yet exist: %s') % (name, ref))
dependencies = [ref] + self.recursive_depends[ref]
self.recursive_depends[name] += dependencies
self.defined_filters.append(name)
return True
self.fake_libvirt_connection.nwfilterDefineXML = _filterDefineXMLMock
instance_ref = self._create_instance()
inst_id = instance_ref['id']
inst_uuid = instance_ref['uuid']
def _ensure_all_called(mac, allow_dhcp):
instance_filter = 'nova-instance-%s-%s' % (instance_ref['name'],
mac.translate(None, ':'))
requiredlist = ['no-arp-spoofing', 'no-ip-spoofing',
'no-mac-spoofing']
if allow_dhcp:
requiredlist.append('allow-dhcp-server')
for required in requiredlist:
self.assertTrue(required in
self.recursive_depends[instance_filter],
"Instance's filter does not include %s" %
required)
self.security_group = self.setup_and_return_security_group()
db.instance_add_security_group(self.context, inst_uuid,
self.security_group['id'])
instance = db.instance_get(self.context, inst_id)
network_info = _fake_network_info(self.stubs, 1)
# since there is one (network_info) there is one vif
# pass this vif's mac to _ensure_all_called()
# to set the instance_filter properly
mac = network_info[0][1]['mac']
self.fw.setup_basic_filtering(instance, network_info)
allow_dhcp = False
for (network, mapping) in network_info:
if mapping['dhcp_server']:
allow_dhcp = True
break
_ensure_all_called(mac, allow_dhcp)
db.instance_remove_security_group(self.context, inst_uuid,
self.security_group['id'])
self.teardown_security_group()
db.instance_destroy(context.get_admin_context(), instance_ref['uuid'])
def test_unfilter_instance_undefines_nwfilters(self):
admin_ctxt = context.get_admin_context()
fakefilter = NWFilterFakes()
self.fw._conn.nwfilterDefineXML = fakefilter.filterDefineXMLMock
self.fw._conn.nwfilterLookupByName = fakefilter.nwfilterLookupByName
instance_ref = self._create_instance()
inst_id = instance_ref['id']
inst_uuid = instance_ref['uuid']
self.security_group = self.setup_and_return_security_group()
db.instance_add_security_group(self.context, inst_uuid,
self.security_group['id'])
instance = db.instance_get(self.context, inst_id)
network_info = _fake_network_info(self.stubs, 1)
self.fw.setup_basic_filtering(instance, network_info)
original_filter_count = len(fakefilter.filters)
self.fw.unfilter_instance(instance, network_info)
self.assertEqual(original_filter_count - len(fakefilter.filters), 1)
db.instance_destroy(admin_ctxt, instance_ref['uuid'])
def test_nwfilter_parameters(self):
admin_ctxt = context.get_admin_context()
fakefilter = NWFilterFakes()
self.fw._conn.nwfilterDefineXML = fakefilter.filterDefineXMLMock
self.fw._conn.nwfilterLookupByName = fakefilter.nwfilterLookupByName
instance_ref = self._create_instance()
inst_id = instance_ref['id']
inst_uuid = instance_ref['uuid']
self.security_group = self.setup_and_return_security_group()
db.instance_add_security_group(self.context, inst_uuid,
self.security_group['id'])
instance = db.instance_get(self.context, inst_id)
network_info = _fake_network_info(self.stubs, 1)
self.fw.setup_basic_filtering(instance, network_info)
(network, mapping) = network_info[0]
nic_id = mapping['mac'].replace(':', '')
instance_filter_name = self.fw._instance_filter_name(instance, nic_id)
f = fakefilter.nwfilterLookupByName(instance_filter_name)
tree = etree.fromstring(f.xml)
for fref in tree.findall('filterref'):
parameters = fref.findall('./parameter')
for parameter in parameters:
if parameter.get('name') == 'IP':
self.assertTrue(_ipv4_like(parameter.get('value'),
'192.168'))
elif parameter.get('name') == 'DHCPSERVER':
dhcp_server = mapping['dhcp_server']
self.assertEqual(parameter.get('value'), dhcp_server)
elif parameter.get('name') == 'RASERVER':
ra_server = mapping.get('gateway_v6') + "/128"
self.assertEqual(parameter.get('value'), ra_server)
elif parameter.get('name') == 'PROJNET':
ipv4_cidr = network['cidr']
net, mask = netutils.get_net_and_mask(ipv4_cidr)
self.assertEqual(parameter.get('value'), net)
elif parameter.get('name') == 'PROJMASK':
ipv4_cidr = network['cidr']
net, mask = netutils.get_net_and_mask(ipv4_cidr)
self.assertEqual(parameter.get('value'), mask)
elif parameter.get('name') == 'PROJNET6':
ipv6_cidr = network['cidr_v6']
net, prefix = netutils.get_net_and_prefixlen(ipv6_cidr)
self.assertEqual(parameter.get('value'), net)
elif parameter.get('name') == 'PROJMASK6':
ipv6_cidr = network['cidr_v6']
net, prefix = netutils.get_net_and_prefixlen(ipv6_cidr)
self.assertEqual(parameter.get('value'), prefix)
else:
raise exception.InvalidParameterValue('unknown parameter '
'in filter')
db.instance_destroy(admin_ctxt, instance_ref['uuid'])
class LibvirtUtilsTestCase(test.TestCase):
def test_get_iscsi_initiator(self):
self.mox.StubOutWithMock(utils, 'execute')
initiator = 'fake.initiator.iqn'
rval = ("junk\nInitiatorName=%s\njunk\n" % initiator, None)
utils.execute('cat', '/etc/iscsi/initiatorname.iscsi',
run_as_root=True).AndReturn(rval)
# Start test
self.mox.ReplayAll()
result = libvirt_utils.get_iscsi_initiator()
self.assertEqual(initiator, result)
def test_create_image(self):
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('qemu-img', 'create', '-f', 'raw',
'/some/path', '10G')
utils.execute('qemu-img', 'create', '-f', 'qcow2',
'/some/stuff', '1234567891234')
# Start test
self.mox.ReplayAll()
libvirt_utils.create_image('raw', '/some/path', '10G')
libvirt_utils.create_image('qcow2', '/some/stuff', '1234567891234')
def test_create_cow_image(self):
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(utils, 'execute')
rval = ('', '')
os.path.exists('/some/path').AndReturn(True)
utils.execute('env', 'LC_ALL=C', 'LANG=C',
'qemu-img', 'info', '/some/path').AndReturn(rval)
utils.execute('qemu-img', 'create', '-f', 'qcow2',
'-o', 'backing_file=/some/path',
'/the/new/cow')
# Start test
self.mox.ReplayAll()
libvirt_utils.create_cow_image('/some/path', '/the/new/cow')
def test_pick_disk_driver_name(self):
type_map = {'kvm': ([True, 'qemu'], [False, 'qemu'], [None, 'qemu']),
'qemu': ([True, 'qemu'], [False, 'qemu'], [None, 'qemu']),
'xen': ([True, 'phy'], [False, 'tap'], [None, 'tap']),
'uml': ([True, None], [False, None], [None, None]),
'lxc': ([True, None], [False, None], [None, None])}
for (libvirt_type, checks) in type_map.iteritems():
self.flags(libvirt_type=libvirt_type)
for (is_block_dev, expected_result) in checks:
result = libvirt_utils.pick_disk_driver_name(is_block_dev)
self.assertEquals(result, expected_result)
def test_get_disk_size(self):
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(utils, 'execute')
os.path.exists('/some/path').AndReturn(True)
utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
'/some/path').AndReturn(('''image: 00000001
file format: raw
virtual size: 4.4M (4592640 bytes)
disk size: 4.4M''', ''))
# Start test
self.mox.ReplayAll()
self.assertEquals(disk.get_disk_size('/some/path'), 4592640)
def test_copy_image(self):
dst_fd, dst_path = tempfile.mkstemp()
try:
os.close(dst_fd)
src_fd, src_path = tempfile.mkstemp()
try:
with os.fdopen(src_fd, 'w') as fp:
fp.write('canary')
libvirt_utils.copy_image(src_path, dst_path)
with open(dst_path, 'r') as fp:
self.assertEquals(fp.read(), 'canary')
finally:
os.unlink(src_path)
finally:
os.unlink(dst_path)
def test_write_to_file(self):
dst_fd, dst_path = tempfile.mkstemp()
try:
os.close(dst_fd)
libvirt_utils.write_to_file(dst_path, 'hello')
with open(dst_path, 'r') as fp:
self.assertEquals(fp.read(), 'hello')
finally:
os.unlink(dst_path)
def test_write_to_file_with_umask(self):
dst_fd, dst_path = tempfile.mkstemp()
try:
os.close(dst_fd)
os.unlink(dst_path)
libvirt_utils.write_to_file(dst_path, 'hello', umask=0277)
with open(dst_path, 'r') as fp:
self.assertEquals(fp.read(), 'hello')
mode = os.stat(dst_path).st_mode
self.assertEquals(mode & 0277, 0)
finally:
os.unlink(dst_path)
def test_chown(self):
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('chown', 'soren', '/some/path', run_as_root=True)
self.mox.ReplayAll()
libvirt_utils.chown('/some/path', 'soren')
def _do_test_extract_snapshot(self, dest_format='raw', out_format='raw'):
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('qemu-img', 'convert', '-f', 'qcow2', '-O', out_format,
'-s', 'snap1', '/path/to/disk/image', '/extracted/snap')
# Start test
self.mox.ReplayAll()
libvirt_utils.extract_snapshot('/path/to/disk/image', 'qcow2',
'snap1', '/extracted/snap', dest_format)
def test_extract_snapshot_raw(self):
self._do_test_extract_snapshot()
def test_extract_snapshot_iso(self):
self._do_test_extract_snapshot(dest_format='iso')
def test_extract_snapshot_qcow2(self):
self._do_test_extract_snapshot(dest_format='qcow2', out_format='qcow2')
def test_load_file(self):
dst_fd, dst_path = tempfile.mkstemp()
try:
os.close(dst_fd)
# We have a test for write_to_file. If that is sound, this suffices
libvirt_utils.write_to_file(dst_path, 'hello')
self.assertEquals(libvirt_utils.load_file(dst_path), 'hello')
finally:
os.unlink(dst_path)
def test_file_open(self):
dst_fd, dst_path = tempfile.mkstemp()
try:
os.close(dst_fd)
# We have a test for write_to_file. If that is sound, this suffices
libvirt_utils.write_to_file(dst_path, 'hello')
with libvirt_utils.file_open(dst_path, 'r') as fp:
self.assertEquals(fp.read(), 'hello')
finally:
os.unlink(dst_path)
def test_get_fs_info(self):
class FakeStatResult(object):
def __init__(self):
self.f_bsize = 4096
self.f_frsize = 4096
self.f_blocks = 2000
self.f_bfree = 1000
self.f_bavail = 900
self.f_files = 2000
self.f_ffree = 1000
self.f_favail = 900
self.f_flag = 4096
self.f_namemax = 255
self.path = None
def fake_statvfs(path):
self.path = path
return FakeStatResult()
self.stubs.Set(os, 'statvfs', fake_statvfs)
fs_info = libvirt_utils.get_fs_info('/some/file/path')
self.assertEquals('/some/file/path', self.path)
self.assertEquals(8192000, fs_info['total'])
self.assertEquals(3686400, fs_info['free'])
self.assertEquals(4096000, fs_info['used'])
def test_fetch_image(self):
self.mox.StubOutWithMock(images, 'fetch_to_raw')
context = 'opaque context'
target = '/tmp/targetfile'
image_id = '4'
user_id = 'fake'
project_id = 'fake'
images.fetch_to_raw(context, image_id, target, user_id, project_id)
self.mox.ReplayAll()
libvirt_utils.fetch_image(context, target, image_id,
user_id, project_id)
def test_fetch_raw_image(self):
def fake_execute(*cmd, **kwargs):
self.executes.append(cmd)
return None, None
def fake_rename(old, new):
self.executes.append(('mv', old, new))
def fake_unlink(path):
self.executes.append(('rm', path))
def fake_rm_on_errror(path):
self.executes.append(('rm', '-f', path))
def fake_qemu_img_info(path):
class FakeImgInfo(object):
pass
file_format = path.split('.')[-1]
if file_format == 'part':
file_format = path.split('.')[-2]
elif file_format == 'converted':
file_format = 'raw'
if 'backing' in path:
backing_file = 'backing'
else:
backing_file = None
FakeImgInfo.file_format = file_format
FakeImgInfo.backing_file = backing_file
return FakeImgInfo()
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(os, 'rename', fake_rename)
self.stubs.Set(os, 'unlink', fake_unlink)
self.stubs.Set(images, 'fetch', lambda *_: None)
self.stubs.Set(images, 'qemu_img_info', fake_qemu_img_info)
self.stubs.Set(utils, 'delete_if_exists', fake_rm_on_errror)
context = 'opaque context'
image_id = '4'
user_id = 'fake'
project_id = 'fake'
target = 't.qcow2'
self.executes = []
expected_commands = [('qemu-img', 'convert', '-O', 'raw',
't.qcow2.part', 't.qcow2.converted'),
('rm', 't.qcow2.part'),
('mv', 't.qcow2.converted', 't.qcow2')]
images.fetch_to_raw(context, image_id, target, user_id, project_id)
self.assertEqual(self.executes, expected_commands)
target = 't.raw'
self.executes = []
expected_commands = [('mv', 't.raw.part', 't.raw')]
images.fetch_to_raw(context, image_id, target, user_id, project_id)
self.assertEqual(self.executes, expected_commands)
target = 'backing.qcow2'
self.executes = []
expected_commands = [('rm', '-f', 'backing.qcow2.part')]
self.assertRaises(exception.ImageUnacceptable,
images.fetch_to_raw,
context, image_id, target, user_id, project_id)
self.assertEqual(self.executes, expected_commands)
del self.executes
def test_get_disk_backing_file(self):
with_actual_path = False
def fake_execute(*args, **kwargs):
if with_actual_path:
return ("some: output\n"
"backing file: /foo/bar/baz (actual path: /a/b/c)\n"
"...: ...\n"), ''
else:
return ("some: output\n"
"backing file: /foo/bar/baz\n"
"...: ...\n"), ''
def return_true(*args, **kwargs):
return True
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(os.path, 'exists', return_true)
out = libvirt_utils.get_disk_backing_file('')
self.assertEqual(out, 'baz')
with_actual_path = True
out = libvirt_utils.get_disk_backing_file('')
self.assertEqual(out, 'c')
class LibvirtDriverTestCase(test.TestCase):
"""Test for nova.virt.libvirt.libvirt_driver.LibvirtDriver."""
def setUp(self):
super(LibvirtDriverTestCase, self).setUp()
self.libvirtconnection = libvirt_driver.LibvirtDriver(
fake.FakeVirtAPI(), read_only=True)
def _create_instance(self, params=None):
"""Create a test instance."""
if not params:
params = {}
sys_meta = flavors.save_instance_type_info(
{}, flavors.get_instance_type_by_name('m1.tiny'))
inst = {}
inst['image_ref'] = '1'
inst['reservation_id'] = 'r-fakeres'
inst['launch_time'] = '10'
inst['user_id'] = 'fake'
inst['project_id'] = 'fake'
type_id = flavors.get_instance_type_by_name('m1.tiny')['id']
inst['instance_type_id'] = type_id
inst['ami_launch_index'] = 0
inst['host'] = 'host1'
inst['root_gb'] = 10
inst['ephemeral_gb'] = 20
inst['config_drive'] = 1
inst['kernel_id'] = 2
inst['ramdisk_id'] = 3
inst['config_drive_id'] = 1
inst['key_data'] = 'ABCDEFG'
inst['system_metadata'] = sys_meta
inst.update(params)
return db.instance_create(context.get_admin_context(), inst)
def test_migrate_disk_and_power_off_exception(self):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.migrate_disk_and_power_off. """
self.counter = 0
self.checked_shared_storage = False
def fake_get_instance_disk_info(instance, xml=None):
return '[]'
def fake_destroy(instance):
pass
def fake_get_host_ip_addr():
return '10.0.0.1'
def fake_execute(*args, **kwargs):
self.counter += 1
if self.counter == 1:
assert False, "intentional failure"
def fake_os_path_exists(path):
return True
def fake_is_storage_shared(dest, inst_base):
self.checked_shared_storage = True
return False
self.stubs.Set(self.libvirtconnection, 'get_instance_disk_info',
fake_get_instance_disk_info)
self.stubs.Set(self.libvirtconnection, '_destroy', fake_destroy)
self.stubs.Set(self.libvirtconnection, 'get_host_ip_addr',
fake_get_host_ip_addr)
self.stubs.Set(self.libvirtconnection, '_is_storage_shared_with',
fake_is_storage_shared)
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(os.path, 'exists', fake_os_path_exists)
ins_ref = self._create_instance()
self.assertRaises(AssertionError,
self.libvirtconnection.migrate_disk_and_power_off,
None, ins_ref, '10.0.0.2', None, None)
def test_migrate_disk_and_power_off(self):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.migrate_disk_and_power_off. """
disk_info = [{'type': 'qcow2', 'path': '/test/disk',
'virt_disk_size': '10737418240',
'backing_file': '/base/disk',
'disk_size': '83886080'},
{'type': 'raw', 'path': '/test/disk.local',
'virt_disk_size': '10737418240',
'backing_file': '/base/disk.local',
'disk_size': '83886080'}]
disk_info_text = jsonutils.dumps(disk_info)
def fake_get_instance_disk_info(instance, xml=None):
return disk_info_text
def fake_destroy(instance):
pass
def fake_get_host_ip_addr():
return '10.0.0.1'
def fake_execute(*args, **kwargs):
pass
self.stubs.Set(self.libvirtconnection, 'get_instance_disk_info',
fake_get_instance_disk_info)
self.stubs.Set(self.libvirtconnection, '_destroy', fake_destroy)
self.stubs.Set(self.libvirtconnection, 'get_host_ip_addr',
fake_get_host_ip_addr)
self.stubs.Set(utils, 'execute', fake_execute)
ins_ref = self._create_instance()
# dest is different host case
out = self.libvirtconnection.migrate_disk_and_power_off(
None, ins_ref, '10.0.0.2', None, None)
self.assertEquals(out, disk_info_text)
# dest is same host case
out = self.libvirtconnection.migrate_disk_and_power_off(
None, ins_ref, '10.0.0.1', None, None)
self.assertEquals(out, disk_info_text)
def test_wait_for_running(self):
def fake_get_info(instance):
if instance['name'] == "not_found":
raise exception.NotFound
elif instance['name'] == "running":
return {'state': power_state.RUNNING}
else:
return {'state': power_state.SHUTDOWN}
self.stubs.Set(self.libvirtconnection, 'get_info',
fake_get_info)
# instance not found case
self.assertRaises(exception.NotFound,
self.libvirtconnection._wait_for_running,
{'name': 'not_found',
'uuid': 'not_found_uuid'})
# instance is running case
self.assertRaises(loopingcall.LoopingCallDone,
self.libvirtconnection._wait_for_running,
{'name': 'running',
'uuid': 'running_uuid'})
# else case
self.libvirtconnection._wait_for_running({'name': 'else',
'uuid': 'other_uuid'})
def test_finish_migration(self):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.finish_migration. """
disk_info = [{'type': 'qcow2', 'path': '/test/disk',
'local_gb': 10, 'backing_file': '/base/disk'},
{'type': 'raw', 'path': '/test/disk.local',
'local_gb': 10, 'backing_file': '/base/disk.local'}]
disk_info_text = jsonutils.dumps(disk_info)
def fake_can_resize_fs(path, size, use_cow=False):
return False
def fake_extend(path, size):
pass
def fake_to_xml(instance, network_info, disk_info,
image_meta=None, rescue=None,
block_device_info=None, write_to_disk=False):
return ""
def fake_plug_vifs(instance, network_info):
pass
def fake_create_image(context, inst,
disk_mapping, suffix='',
disk_images=None, network_info=None,
block_device_info=None):
pass
def fake_create_domain(xml, instance=None):
return None
def fake_enable_hairpin(instance):
pass
def fake_execute(*args, **kwargs):
pass
def fake_get_info(instance):
return {'state': power_state.RUNNING}
self.flags(use_cow_images=True)
self.stubs.Set(libvirt_driver.disk, 'extend', fake_extend)
self.stubs.Set(libvirt_driver.disk, 'can_resize_fs',
fake_can_resize_fs)
self.stubs.Set(self.libvirtconnection, 'to_xml', fake_to_xml)
self.stubs.Set(self.libvirtconnection, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(self.libvirtconnection, '_create_image',
fake_create_image)
self.stubs.Set(self.libvirtconnection, '_create_domain',
fake_create_domain)
self.stubs.Set(self.libvirtconnection, '_enable_hairpin',
fake_enable_hairpin)
self.stubs.Set(utils, 'execute', fake_execute)
fw = base_firewall.NoopFirewallDriver()
self.stubs.Set(self.libvirtconnection, 'firewall_driver', fw)
self.stubs.Set(self.libvirtconnection, 'get_info',
fake_get_info)
ins_ref = self._create_instance()
self.libvirtconnection.finish_migration(
context.get_admin_context(), None, ins_ref,
disk_info_text, None, None, None)
def test_finish_revert_migration(self):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.finish_revert_migration. """
def fake_execute(*args, **kwargs):
pass
def fake_plug_vifs(instance, network_info):
pass
def fake_create_domain(xml, instance=None):
return None
def fake_enable_hairpin(instance):
pass
def fake_get_info(instance):
return {'state': power_state.RUNNING}
def fake_to_xml(instance, network_info, disk_info,
image_meta=None, rescue=None,
block_device_info=None):
return ""
self.stubs.Set(self.libvirtconnection, 'to_xml', fake_to_xml)
self.stubs.Set(self.libvirtconnection, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(utils, 'execute', fake_execute)
fw = base_firewall.NoopFirewallDriver()
self.stubs.Set(self.libvirtconnection, 'firewall_driver', fw)
self.stubs.Set(self.libvirtconnection, '_create_domain',
fake_create_domain)
self.stubs.Set(self.libvirtconnection, '_enable_hairpin',
fake_enable_hairpin)
self.stubs.Set(self.libvirtconnection, 'get_info',
fake_get_info)
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
ins_ref = self._create_instance()
os.mkdir(os.path.join(tmpdir, ins_ref['name']))
libvirt_xml_path = os.path.join(tmpdir,
ins_ref['name'],
'libvirt.xml')
f = open(libvirt_xml_path, 'w')
f.close()
self.libvirtconnection.finish_revert_migration(ins_ref, None)
def _test_finish_revert_migration_after_crash(self, backup_made, new_made):
class FakeLoopingCall:
def start(self, *a, **k):
return self
def wait(self):
return None
self.mox.StubOutWithMock(libvirt_utils, 'get_instance_path')
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(shutil, 'rmtree')
self.mox.StubOutWithMock(utils, 'execute')
self.stubs.Set(blockinfo, 'get_disk_info', lambda *a: None)
self.stubs.Set(self.libvirtconnection, 'to_xml', lambda *a, **k: None)
self.stubs.Set(self.libvirtconnection, '_create_domain_and_network',
lambda *a: None)
self.stubs.Set(loopingcall, 'FixedIntervalLoopingCall',
lambda *a, **k: FakeLoopingCall())
libvirt_utils.get_instance_path({}).AndReturn('/fake/foo')
os.path.exists('/fake/foo_resize').AndReturn(backup_made)
if backup_made:
os.path.exists('/fake/foo').AndReturn(new_made)
if new_made:
shutil.rmtree('/fake/foo')
utils.execute('mv', '/fake/foo_resize', '/fake/foo')
self.mox.ReplayAll()
self.libvirtconnection.finish_revert_migration({}, [])
def test_finish_revert_migration_after_crash(self):
self._test_finish_revert_migration_after_crash(True, True)
def test_finish_revert_migration_after_crash_before_new(self):
self._test_finish_revert_migration_after_crash(True, False)
def test_finish_revert_migration_after_crash_before_backup(self):
self._test_finish_revert_migration_after_crash(False, False)
def test_cleanup_failed_migration(self):
self.mox.StubOutWithMock(shutil, 'rmtree')
shutil.rmtree('/fake/inst')
self.mox.ReplayAll()
self.libvirtconnection._cleanup_failed_migration('/fake/inst')
def test_confirm_migration(self):
ins_ref = self._create_instance()
self.mox.StubOutWithMock(self.libvirtconnection, "_cleanup_resize")
self.libvirtconnection._cleanup_resize(ins_ref,
_fake_network_info(self.stubs, 1))
self.mox.ReplayAll()
self.libvirtconnection.confirm_migration("migration_ref", ins_ref,
_fake_network_info(self.stubs, 1))
def test_cleanup_resize_same_host(self):
ins_ref = self._create_instance({'host': CONF.host})
def fake_os_path_exists(path):
return True
def fake_shutil_rmtree(target):
pass
self.stubs.Set(os.path, 'exists', fake_os_path_exists)
self.stubs.Set(shutil, 'rmtree', fake_shutil_rmtree)
self.mox.ReplayAll()
self.libvirtconnection._cleanup_resize(ins_ref,
_fake_network_info(self.stubs, 1))
def test_cleanup_resize_not_same_host(self):
host = 'not' + CONF.host
ins_ref = self._create_instance({'host': host})
def fake_os_path_exists(path):
return True
def fake_shutil_rmtree(target):
pass
def fake_undefine_domain(instance):
pass
def fake_unplug_vifs(instance, network_info):
pass
def fake_unfilter_instance(instance, network_info):
pass
self.stubs.Set(os.path, 'exists', fake_os_path_exists)
self.stubs.Set(shutil, 'rmtree', fake_shutil_rmtree)
self.stubs.Set(self.libvirtconnection, '_undefine_domain',
fake_undefine_domain)
self.stubs.Set(self.libvirtconnection, 'unplug_vifs',
fake_unplug_vifs)
self.stubs.Set(self.libvirtconnection.firewall_driver,
'unfilter_instance', fake_unfilter_instance)
self.mox.ReplayAll()
self.libvirtconnection._cleanup_resize(ins_ref,
_fake_network_info(self.stubs, 1))
def test_get_instance_disk_info_exception(self):
instance_name = "fake-instance-name"
class FakeExceptionDomain(FakeVirtDomain):
def __init__(self):
super(FakeExceptionDomain, self).__init__()
def XMLDesc(self, *args):
raise libvirt.libvirtError("Libvirt error")
def fake_lookup_by_name(instance_name):
return FakeExceptionDomain()
self.stubs.Set(self.libvirtconnection, '_lookup_by_name',
fake_lookup_by_name)
self.assertRaises(exception.InstanceNotFound,
self.libvirtconnection.get_instance_disk_info,
instance_name)
def test_get_cpuset_ids(self):
# correct syntax
self.flags(vcpu_pin_set="1")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1], cpuset_ids)
self.flags(vcpu_pin_set="1,2")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1, 2], cpuset_ids)
self.flags(vcpu_pin_set=", , 1 , ,, 2, ,")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1, 2], cpuset_ids)
self.flags(vcpu_pin_set="1-1")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1], cpuset_ids)
self.flags(vcpu_pin_set=" 1 - 1, 1 - 2 , 1 -3")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1, 2, 3], cpuset_ids)
self.flags(vcpu_pin_set="1,^2")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1], cpuset_ids)
self.flags(vcpu_pin_set="1-2, ^1")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([2], cpuset_ids)
self.flags(vcpu_pin_set="1-3,5,^2")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1, 3, 5], cpuset_ids)
self.flags(vcpu_pin_set=" 1 - 3 , ^2, 5")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1, 3, 5], cpuset_ids)
# invalid syntax
self.flags(vcpu_pin_set=" -1-3,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-3-,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="-3,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-3,5,^2^")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-3,5,^2-")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="--13,^^5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="a-3,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-a,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-3,b,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-3,5,^c")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="3 - 1, 5 , ^ 2 ")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set=" 1,1, ^1")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set=" 1,^1,^1,2, ^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
class LibvirtVolumeUsageTestCase(test.TestCase):
"""Test for nova.virt.libvirt.libvirt_driver.LibvirtDriver
.get_all_volume_usage"""
def setUp(self):
super(LibvirtVolumeUsageTestCase, self).setUp()
self.conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.c = context.get_admin_context()
# creating instance
inst = {}
inst['uuid'] = '875a8070-d0b9-4949-8b31-104d125c9a64'
self.ins_ref = db.instance_create(self.c, inst)
# verify bootable volume device path also
self.bdms = [{'volume_id': 1,
'device_name': '/dev/vde'},
{'volume_id': 2,
'device_name': 'vda'}]
def test_get_all_volume_usage(self):
def fake_block_stats(instance_name, disk):
return (169L, 688640L, 0L, 0L, -1L)
self.stubs.Set(self.conn, 'block_stats', fake_block_stats)
vol_usage = self.conn.get_all_volume_usage(self.c,
[dict(instance=self.ins_ref, instance_bdms=self.bdms)])
expected_usage = [{'volume': 1,
'instance': self.ins_ref,
'rd_bytes': 688640L, 'wr_req': 0L,
'flush_operations': -1L, 'rd_req': 169L,
'wr_bytes': 0L},
{'volume': 2,
'instance': self.ins_ref,
'rd_bytes': 688640L, 'wr_req': 0L,
'flush_operations': -1L, 'rd_req': 169L,
'wr_bytes': 0L}]
self.assertEqual(vol_usage, expected_usage)
def test_get_all_volume_usage_device_not_found(self):
def fake_lookup(instance_name):
raise libvirt.libvirtError('invalid path')
self.stubs.Set(self.conn, '_lookup_by_name', fake_lookup)
vol_usage = self.conn.get_all_volume_usage(self.c,
[dict(instance=self.ins_ref, instance_bdms=self.bdms)])
self.assertEqual(vol_usage, [])
class LibvirtNonblockingTestCase(test.TestCase):
"""Test libvirt_nonblocking option."""
def setUp(self):
super(LibvirtNonblockingTestCase, self).setUp()
self.flags(libvirt_nonblocking=True, libvirt_uri="test:///default")
def test_connection_to_primitive(self):
# Test bug 962840.
import nova.virt.libvirt.driver as libvirt_driver
connection = libvirt_driver.LibvirtDriver('')
jsonutils.to_primitive(connection._conn, convert_instances=True)
| 41.517087 | 79 | 0.568962 |
import copy
import errno
import eventlet
import fixtures
import json
import mox
import os
import re
import shutil
import tempfile
from lxml import etree
from oslo.config import cfg
from xml.dom import minidom
from nova.api.ec2 import cloud
from nova.compute import flavors
from nova.compute import power_state
from nova.compute import task_states
from nova.compute import vm_mode
from nova.compute import vm_states
from nova import context
from nova import db
from nova import exception
from nova.openstack.common import fileutils
from nova.openstack.common import importutils
from nova.openstack.common import jsonutils
from nova.openstack.common import loopingcall
from nova.openstack.common import uuidutils
from nova import test
from nova.tests import fake_network
import nova.tests.image.fake
from nova.tests import matchers
from nova.tests.virt.libvirt import fake_libvirt_utils
from nova import utils
from nova import version
from nova.virt.disk import api as disk
from nova.virt import driver
from nova.virt import event as virtevent
from nova.virt import fake
from nova.virt import firewall as base_firewall
from nova.virt import images
from nova.virt.libvirt import blockinfo
from nova.virt.libvirt import config as vconfig
from nova.virt.libvirt import driver as libvirt_driver
from nova.virt.libvirt import firewall
from nova.virt.libvirt import imagebackend
from nova.virt.libvirt import utils as libvirt_utils
from nova.virt import netutils
try:
import libvirt
except ImportError:
import nova.tests.virt.libvirt.fakelibvirt as libvirt
libvirt_driver.libvirt = libvirt
CONF = cfg.CONF
CONF.import_opt('compute_manager', 'nova.service')
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')
CONF.import_opt('base_dir_name', 'nova.virt.libvirt.imagecache')
_fake_network_info = fake_network.fake_get_instance_nw_info
_fake_stub_out_get_nw_info = fake_network.stub_out_nw_api_get_instance_nw_info
_ipv4_like = fake_network.ipv4_like
def _concurrency(signal, wait, done, target):
signal.send()
wait.wait()
done.send()
class FakeVirDomainSnapshot(object):
def __init__(self, dom=None):
self.dom = dom
def delete(self, flags):
pass
class FakeVirtDomain(object):
def __init__(self, fake_xml=None, uuidstr=None):
self.uuidstr = uuidstr
if fake_xml:
self._fake_dom_xml = fake_xml
else:
self._fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
</devices>
</domain>
"""
def name(self):
return "fake-domain %s" % self
def info(self):
return [power_state.RUNNING, None, None, None, None]
def create(self):
pass
def managedSave(self, *args):
pass
def createWithFlags(self, launch_flags):
pass
def XMLDesc(self, *args):
return self._fake_dom_xml
def UUIDString(self):
return self.uuidstr
class CacheConcurrencyTestCase(test.TestCase):
def setUp(self):
super(CacheConcurrencyTestCase, self).setUp()
self.flags(instances_path=self.useFixture(fixtures.TempDir()).path)
self.lock_path = os.path.join(CONF.instances_path, 'locks')
fileutils.ensure_tree(self.lock_path)
def fake_exists(fname):
basedir = os.path.join(CONF.instances_path, CONF.base_dir_name)
if fname == basedir or fname == self.lock_path:
return True
return False
def fake_execute(*args, **kwargs):
pass
def fake_extend(image, size):
pass
self.stubs.Set(os.path, 'exists', fake_exists)
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(imagebackend.disk, 'extend', fake_extend)
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
def test_same_fname_concurrency(self):
# Ensures that the same fname cache runs at a sequentially.
uuid = uuidutils.generate_uuid()
backend = imagebackend.Backend(False)
wait1 = eventlet.event.Event()
done1 = eventlet.event.Event()
sig1 = eventlet.event.Event()
thr1 = eventlet.spawn(backend.image({'name': 'instance',
'uuid': uuid},
'name').cache,
_concurrency, 'fname', None,
signal=sig1, wait=wait1, done=done1)
eventlet.sleep(0)
# Thread 1 should run before thread 2.
sig1.wait()
wait2 = eventlet.event.Event()
done2 = eventlet.event.Event()
sig2 = eventlet.event.Event()
thr2 = eventlet.spawn(backend.image({'name': 'instance',
'uuid': uuid},
'name').cache,
_concurrency, 'fname', None,
signal=sig2, wait=wait2, done=done2)
wait2.send()
eventlet.sleep(0)
try:
self.assertFalse(done2.ready())
finally:
wait1.send()
done1.wait()
eventlet.sleep(0)
self.assertTrue(done2.ready())
# Wait on greenthreads to assert they didn't raise exceptions
thr1.wait()
thr2.wait()
def test_different_fname_concurrency(self):
uuid = uuidutils.generate_uuid()
backend = imagebackend.Backend(False)
wait1 = eventlet.event.Event()
done1 = eventlet.event.Event()
sig1 = eventlet.event.Event()
thr1 = eventlet.spawn(backend.image({'name': 'instance',
'uuid': uuid},
'name').cache,
_concurrency, 'fname2', None,
signal=sig1, wait=wait1, done=done1)
eventlet.sleep(0)
sig1.wait()
wait2 = eventlet.event.Event()
done2 = eventlet.event.Event()
sig2 = eventlet.event.Event()
thr2 = eventlet.spawn(backend.image({'name': 'instance',
'uuid': uuid},
'name').cache,
_concurrency, 'fname1', None,
signal=sig2, wait=wait2, done=done2)
eventlet.sleep(0)
sig2.wait()
wait2.send()
eventlet.sleep(0)
try:
self.assertTrue(done2.ready())
finally:
wait1.send()
eventlet.sleep(0)
# during execution
thr1.wait()
thr2.wait()
class FakeVolumeDriver(object):
def __init__(self, *args, **kwargs):
pass
def attach_volume(self, *args):
pass
def detach_volume(self, *args):
pass
def get_xml(self, *args):
return ""
class FakeConfigGuestDisk(object):
def __init__(self, *args, **kwargs):
self.source_type = None
self.driver_cache = None
class FakeConfigGuest(object):
def __init__(self, *args, **kwargs):
self.driver_cache = None
class LibvirtConnTestCase(test.TestCase):
def setUp(self):
super(LibvirtConnTestCase, self).setUp()
self.flags(fake_call=True)
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.get_admin_context()
self.flags(instances_path='')
self.flags(libvirt_snapshots_directory='')
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.libvirt_utils',
fake_libvirt_utils))
# Force libvirt to return a host UUID that matches the serial in
# nova.tests.fakelibvirt. This is necessary because the host UUID
# returned by libvirt becomes the serial whose value is checked for in
# test_xml_and_uri_* below.
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.LibvirtDriver.get_host_uuid',
lambda _: 'cef19ce0-0ca2-11df-855d-b19fbce37686'))
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
def fake_extend(image, size):
pass
self.stubs.Set(libvirt_driver.disk, 'extend', fake_extend)
class FakeConn():
def getCapabilities(self):
return """<capabilities>
<host><cpu><arch>x86_64</arch></cpu></host>
</capabilities>"""
def getLibVersion(self):
return (0 * 1000 * 1000) + (9 * 1000) + 11
self.conn = FakeConn()
self.stubs.Set(libvirt_driver.LibvirtDriver, '_connect',
lambda *a, **k: self.conn)
instance_type = db.instance_type_get(self.context, 5)
sys_meta = flavors.save_instance_type_info({}, instance_type)
nova.tests.image.fake.stub_out_image_service(self.stubs)
self.test_instance = {
'uuid': '32dfcb37-5af1-552b-357c-be8c3aa38310',
'memory_kb': '1024000',
'basepath': '/some/path',
'bridge_name': 'br100',
'vcpus': 2,
'project_id': 'fake',
'bridge': 'br101',
'image_ref': '155d900f-4e14-4e4c-a73d-069cbf4541e6',
'root_gb': 10,
'ephemeral_gb': 20,
'instance_type_id': '5', # m1.small
'extra_specs': {},
'system_metadata': sys_meta}
def tearDown(self):
nova.tests.image.fake.FakeImageService_reset()
super(LibvirtConnTestCase, self).tearDown()
def create_fake_libvirt_mock(self, **kwargs):
"""Defining mocks for LibvirtDriver(libvirt is not used)."""
# A fake libvirt.virConnect
class FakeLibvirtDriver(object):
def defineXML(self, xml):
return FakeVirtDomain()
# Creating mocks
volume_driver = ('iscsi=nova.tests.virt.libvirt.test_libvirt'
'.FakeVolumeDriver')
self.flags(libvirt_volume_drivers=[volume_driver])
fake = FakeLibvirtDriver()
# Customizing above fake if necessary
for key, val in kwargs.items():
fake.__setattr__(key, val)
self.flags(libvirt_vif_driver="nova.tests.fake_network.FakeVIFDriver")
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn = fake
def fake_lookup(self, instance_name):
return FakeVirtDomain()
def fake_execute(self, *args, **kwargs):
open(args[-1], "a").close()
def create_service(self, **kwargs):
service_ref = {'host': kwargs.get('host', 'dummy'),
'binary': 'nova-compute',
'topic': 'compute',
'report_count': 0}
return db.service_create(context.get_admin_context(), service_ref)
def test_get_connector(self):
initiator = 'fake.initiator.iqn'
ip = 'fakeip'
host = 'fakehost'
wwpns = ['100010604b019419']
wwnns = ['200010604b019419']
self.flags(my_ip=ip)
self.flags(host=host)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
expected = {
'ip': ip,
'initiator': initiator,
'host': host,
'wwpns': wwpns,
'wwnns': wwnns
}
volume = {
'id': 'fake'
}
result = conn.get_volume_connector(volume)
self.assertThat(expected, matchers.DictMatches(result))
def test_get_guest_config(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(cfg.acpi, True)
self.assertEquals(cfg.apic, True)
self.assertEquals(cfg.memory, 1024 * 1024 * 2)
self.assertEquals(cfg.vcpus, 1)
self.assertEquals(cfg.os_type, vm_mode.HVM)
self.assertEquals(cfg.os_boot_dev, "hd")
self.assertEquals(cfg.os_root, None)
self.assertEquals(len(cfg.devices), 7)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestInterface)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestInput)
self.assertEquals(type(cfg.devices[6]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(type(cfg.clock),
vconfig.LibvirtConfigGuestClock)
self.assertEquals(cfg.clock.offset, "utc")
self.assertEquals(len(cfg.clock.timers), 2)
self.assertEquals(type(cfg.clock.timers[0]),
vconfig.LibvirtConfigGuestTimer)
self.assertEquals(type(cfg.clock.timers[1]),
vconfig.LibvirtConfigGuestTimer)
self.assertEquals(cfg.clock.timers[0].name, "pit")
self.assertEquals(cfg.clock.timers[0].tickpolicy,
"delay")
self.assertEquals(cfg.clock.timers[1].name, "rtc")
self.assertEquals(cfg.clock.timers[1].tickpolicy,
"catchup")
def test_get_guest_config_with_two_nics(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 2),
None, disk_info)
self.assertEquals(cfg.acpi, True)
self.assertEquals(cfg.memory, 1024 * 1024 * 2)
self.assertEquals(cfg.vcpus, 1)
self.assertEquals(cfg.os_type, vm_mode.HVM)
self.assertEquals(cfg.os_boot_dev, "hd")
self.assertEquals(cfg.os_root, None)
self.assertEquals(len(cfg.devices), 8)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestInterface)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestInterface)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[6]),
vconfig.LibvirtConfigGuestInput)
self.assertEquals(type(cfg.devices[7]),
vconfig.LibvirtConfigGuestGraphics)
def test_get_guest_config_bug_1118829(self):
self.flags(libvirt_type='uml')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = {'disk_bus': 'virtio',
'cdrom_bus': 'ide',
'mapping': {u'vda': {'bus': 'virtio',
'type': 'disk',
'dev': u'vda'},
'root': {'bus': 'virtio',
'type': 'disk',
'dev': 'vda'}}}
# NOTE(jdg): For this specific test leave this blank
# This will exercise the failed code path still,
# and won't require fakes and stubs of the iscsi discovery
block_device_info = {}
cfg = conn.get_guest_config(instance_ref, [], None, disk_info,
None, block_device_info)
instance_ref = db.instance_get(self.context, instance_ref['id'])
self.assertEquals(instance_ref['root_device_name'], '/dev/vda')
def test_get_guest_config_with_root_device_name(self):
self.flags(libvirt_type='uml')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
block_device_info = {'root_device_name': '/dev/vdb'}
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref,
block_device_info)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info,
None, block_device_info)
self.assertEquals(cfg.acpi, False)
self.assertEquals(cfg.memory, 1024 * 1024 * 2)
self.assertEquals(cfg.vcpus, 1)
self.assertEquals(cfg.os_type, "uml")
self.assertEquals(cfg.os_boot_dev, None)
self.assertEquals(cfg.os_root, '/dev/vdb')
self.assertEquals(len(cfg.devices), 3)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestConsole)
def test_get_guest_config_with_block_device(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
conn_info = {'driver_volume_type': 'fake'}
info = {'block_device_mapping': [
{'connection_info': conn_info, 'mount_device': '/dev/vdc'},
{'connection_info': conn_info, 'mount_device': '/dev/vdd'}]}
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref, info)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info,
None, info)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(cfg.devices[2].target_dev, 'vdc')
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(cfg.devices[3].target_dev, 'vdd')
def test_get_guest_config_with_configdrive(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
instance_ref['config_drive'] = 'ANY_ID'
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(cfg.devices[2].target_dev, 'vdz')
def test_get_guest_config_with_vnc(self):
self.flags(libvirt_type='kvm',
vnc_enabled=True,
use_usb_tablet=False)
self.flags(enabled=False, group='spice')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(len(cfg.devices), 5)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(cfg.devices[4].type, "vnc")
def test_get_guest_config_with_vnc_and_tablet(self):
self.flags(libvirt_type='kvm',
vnc_enabled=True,
use_usb_tablet=True)
self.flags(enabled=False, group='spice')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(len(cfg.devices), 6)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestInput)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(cfg.devices[4].type, "tablet")
self.assertEquals(cfg.devices[5].type, "vnc")
def test_get_guest_config_with_spice_and_tablet(self):
self.flags(libvirt_type='kvm',
vnc_enabled=False,
use_usb_tablet=True)
self.flags(enabled=True,
agent_enabled=False,
group='spice')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(len(cfg.devices), 6)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestInput)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(cfg.devices[4].type, "tablet")
self.assertEquals(cfg.devices[5].type, "spice")
def test_get_guest_config_with_spice_and_agent(self):
self.flags(libvirt_type='kvm',
vnc_enabled=False,
use_usb_tablet=True)
self.flags(enabled=True,
agent_enabled=True,
group='spice')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(len(cfg.devices), 6)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestChannel)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(cfg.devices[4].target_name, "com.redhat.spice.0")
self.assertEquals(cfg.devices[5].type, "spice")
def test_get_guest_config_with_vnc_and_spice(self):
self.flags(libvirt_type='kvm',
vnc_enabled=True,
use_usb_tablet=True)
self.flags(enabled=True,
agent_enabled=True,
group='spice')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
cfg = conn.get_guest_config(instance_ref, [], None, disk_info)
self.assertEquals(len(cfg.devices), 8)
self.assertEquals(type(cfg.devices[0]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[1]),
vconfig.LibvirtConfigGuestDisk)
self.assertEquals(type(cfg.devices[2]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[3]),
vconfig.LibvirtConfigGuestSerial)
self.assertEquals(type(cfg.devices[4]),
vconfig.LibvirtConfigGuestInput)
self.assertEquals(type(cfg.devices[5]),
vconfig.LibvirtConfigGuestChannel)
self.assertEquals(type(cfg.devices[6]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(type(cfg.devices[7]),
vconfig.LibvirtConfigGuestGraphics)
self.assertEquals(cfg.devices[4].type, "tablet")
self.assertEquals(cfg.devices[5].target_name, "com.redhat.spice.0")
self.assertEquals(cfg.devices[6].type, "vnc")
self.assertEquals(cfg.devices[7].type, "spice")
def test_get_guest_cpu_config_none(self):
self.flags(libvirt_cpu_mode="none")
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(conf.cpu, None)
def test_get_guest_cpu_config_default_kvm(self):
self.flags(libvirt_type="kvm",
libvirt_cpu_mode=None)
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 11
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, "host-model")
self.assertEquals(conf.cpu.model, None)
def test_get_guest_cpu_config_default_uml(self):
self.flags(libvirt_type="uml",
libvirt_cpu_mode=None)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(conf.cpu, None)
def test_get_guest_cpu_config_default_lxc(self):
self.flags(libvirt_type="lxc",
libvirt_cpu_mode=None)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(conf.cpu, None)
def test_get_guest_cpu_config_host_passthrough_new(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 11
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="host-passthrough")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, "host-passthrough")
self.assertEquals(conf.cpu.model, None)
def test_get_guest_cpu_config_host_model_new(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 11
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="host-model")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, "host-model")
self.assertEquals(conf.cpu.model, None)
def test_get_guest_cpu_config_custom_new(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 11
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="custom")
self.flags(libvirt_cpu_model="Penryn")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, "custom")
self.assertEquals(conf.cpu.model, "Penryn")
def test_get_guest_cpu_config_host_passthrough_old(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 7
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="host-passthrough")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
self.assertRaises(exception.NovaException,
conn.get_guest_config,
instance_ref,
_fake_network_info(self.stubs, 1),
None,
disk_info)
def test_get_guest_cpu_config_host_model_old(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 7
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.model = "Opteron_G4"
cpu.vendor = "AMD"
cpu.features.append(vconfig.LibvirtConfigGuestCPUFeature("tm2"))
cpu.features.append(vconfig.LibvirtConfigGuestCPUFeature("ht"))
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
return caps
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
self.stubs.Set(libvirt_driver.LibvirtDriver,
"get_host_capabilities",
get_host_capabilities_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="host-model")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, None)
self.assertEquals(conf.cpu.model, "Opteron_G4")
self.assertEquals(conf.cpu.vendor, "AMD")
self.assertEquals(len(conf.cpu.features), 2)
self.assertEquals(conf.cpu.features[0].name, "tm2")
self.assertEquals(conf.cpu.features[1].name, "ht")
def test_get_guest_cpu_config_custom_old(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 7
self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, self.test_instance)
self.flags(libvirt_cpu_mode="custom")
self.flags(libvirt_cpu_model="Penryn")
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
conf = conn.get_guest_config(instance_ref,
_fake_network_info(self.stubs, 1),
None, disk_info)
self.assertEquals(type(conf.cpu),
vconfig.LibvirtConfigGuestCPU)
self.assertEquals(conf.cpu.mode, None)
self.assertEquals(conf.cpu.model, "Penryn")
def test_xml_and_uri_no_ramdisk_no_kernel(self):
instance_data = dict(self.test_instance)
self._check_xml_and_uri(instance_data,
expect_kernel=False, expect_ramdisk=False)
def test_xml_and_uri_no_ramdisk_no_kernel_xen_hvm(self):
instance_data = dict(self.test_instance)
instance_data.update({'vm_mode': vm_mode.HVM})
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, expect_xen_hvm=True)
def test_xml_and_uri_no_ramdisk_no_kernel_xen_pv(self):
instance_data = dict(self.test_instance)
instance_data.update({'vm_mode': vm_mode.XEN})
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, expect_xen_hvm=False,
xen_only=True)
def test_xml_and_uri_no_ramdisk(self):
instance_data = dict(self.test_instance)
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=True, expect_ramdisk=False)
def test_xml_and_uri_no_kernel(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=False, expect_ramdisk=False)
def test_xml_and_uri(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=True, expect_ramdisk=True)
def test_xml_and_uri_rescue(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=True,
expect_ramdisk=True, rescue=instance_data)
def test_xml_and_uri_rescue_no_kernel_no_ramdisk(self):
instance_data = dict(self.test_instance)
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, rescue=instance_data)
def test_xml_and_uri_rescue_no_kernel(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=True, rescue=instance_data)
def test_xml_and_uri_rescue_no_ramdisk(self):
instance_data = dict(self.test_instance)
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=True,
expect_ramdisk=False, rescue=instance_data)
def test_xml_uuid(self):
self._check_xml_and_uuid({"disk_format": "raw"})
def test_lxc_container_and_uri(self):
instance_data = dict(self.test_instance)
self._check_xml_and_container(instance_data)
def test_xml_disk_prefix(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_prefix(instance_data)
def test_xml_user_specified_disk_prefix(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_prefix(instance_data, 'sd')
def test_xml_disk_driver(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_driver(instance_data)
def test_xml_disk_bus_virtio(self):
self._check_xml_and_disk_bus({"disk_format": "raw"},
None,
(("disk", "virtio", "vda"),))
def test_xml_disk_bus_ide(self):
self._check_xml_and_disk_bus({"disk_format": "iso"},
None,
(("cdrom", "ide", "hda"),))
def test_xml_disk_bus_ide_and_virtio(self):
swap = {'device_name': '/dev/vdc',
'swap_size': 1}
ephemerals = [{'num': 0,
'virtual_name': 'ephemeral0',
'device_name': '/dev/vdb',
'size': 1}]
block_device_info = {
'swap': swap,
'ephemerals': ephemerals}
self._check_xml_and_disk_bus({"disk_format": "iso"},
block_device_info,
(("cdrom", "ide", "hda"),
("disk", "virtio", "vdb"),
("disk", "virtio", "vdc")))
def test_list_instances(self):
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByID = self.fake_lookup
libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 2
libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1]
libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: []
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instances = conn.list_instances()
self.assertEquals(len(instances), 1)
def test_list_defined_instances(self):
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByID = self.fake_lookup
libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1
libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0]
libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [1]
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instances = conn.list_instances()
self.assertEquals(len(instances), 1)
def test_list_instances_when_instance_deleted(self):
def fake_lookup(instance_name):
raise libvirt.libvirtError("we deleted an instance!")
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup
libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1
libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1]
libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: []
self.mox.StubOutWithMock(libvirt.libvirtError, "get_error_code")
libvirt.libvirtError.get_error_code().AndReturn(
libvirt.VIR_ERR_NO_DOMAIN)
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instances = conn.list_instances()
self.assertEquals(len(instances), 0)
def test_get_all_block_devices(self):
xml = [
None,
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
</disk>
</devices>
</domain>
""",
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
</devices>
</domain>
""",
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/3'/>
</disk>
</devices>
</domain>
""",
]
def fake_lookup(id):
return FakeVirtDomain(xml[id])
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 4
libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: range(4)
libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
devices = conn.get_all_block_devices()
self.assertEqual(devices, ['/path/to/dev/1', '/path/to/dev/3'])
def test_get_disks(self):
xml = [
None,
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
</devices>
</domain>
""",
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
</devices>
</domain>
""",
"""
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/3'/>
<target dev='vdb' bus='virtio'/>
</disk>
</devices>
</domain>
""",
]
def fake_lookup(id):
return FakeVirtDomain(xml[id])
def fake_lookup_name(name):
return FakeVirtDomain(xml[1])
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 4
libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: range(4)
libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: []
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
devices = conn.get_disks(conn.list_instances()[0])
self.assertEqual(devices, ['vda', 'vdb'])
def test_snapshot_in_ami_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./')
image_service = nova.tests.image.fake.FakeImageService()
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77'
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
libvirt_driver.libvirt_utils.disk_type = "qcow2"
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'ami')
self.assertEquals(snapshot['name'], snapshot_name)
def test_lxc_snapshot_in_ami_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./',
libvirt_type='lxc')
image_service = nova.tests.image.fake.FakeImageService()
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77'
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
libvirt_driver.libvirt_utils.disk_type = "qcow2"
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'ami')
self.assertEquals(snapshot['name'], snapshot_name)
def test_snapshot_in_raw_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./')
image_service = nova.tests.image.fake.FakeImageService()
instance_ref = db.instance_create(self.context, self.test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.stubs.Set(libvirt_driver.libvirt_utils, 'disk_type', 'raw')
def convert_image(source, dest, out_format):
libvirt_driver.libvirt_utils.files[dest] = ''
self.stubs.Set(images, 'convert_image', convert_image)
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'raw')
self.assertEquals(snapshot['name'], snapshot_name)
def test_lxc_snapshot_in_raw_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./',
libvirt_type='lxc')
image_service = nova.tests.image.fake.FakeImageService()
instance_ref = db.instance_create(self.context, self.test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.stubs.Set(libvirt_driver.libvirt_utils, 'disk_type', 'raw')
def convert_image(source, dest, out_format):
libvirt_driver.libvirt_utils.files[dest] = ''
self.stubs.Set(images, 'convert_image', convert_image)
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'raw')
self.assertEquals(snapshot['name'], snapshot_name)
def test_snapshot_in_qcow2_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(snapshot_image_format='qcow2',
libvirt_snapshots_directory='./')
image_service = nova.tests.image.fake.FakeImageService()
instance_ref = db.instance_create(self.context, self.test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
libvirt_driver.libvirt_utils.disk_type = "qcow2"
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'qcow2')
self.assertEquals(snapshot['name'], snapshot_name)
def test_lxc_snapshot_in_qcow2_format(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(snapshot_image_format='qcow2',
libvirt_snapshots_directory='./',
libvirt_type='lxc')
image_service = nova.tests.image.fake.FakeImageService()
instance_ref = db.instance_create(self.context, self.test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
libvirt_driver.libvirt_utils.disk_type = "qcow2"
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['disk_format'], 'qcow2')
self.assertEquals(snapshot['name'], snapshot_name)
def test_snapshot_no_image_architecture(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./')
image_service = nova.tests.image.fake.FakeImageService()
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6'
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['name'], snapshot_name)
def test_lxc_snapshot_no_image_architecture(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./',
libvirt_type='lxc')
image_service = nova.tests.image.fake.FakeImageService()
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6'
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['name'], snapshot_name)
def test_snapshot_no_original_image(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./')
image_service = nova.tests.image.fake.FakeImageService()
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = '661122aa-1234-dede-fefe-babababababa'
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['name'], snapshot_name)
def test_lxc_snapshot_no_original_image(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./',
libvirt_type='lxc')
image_service = nova.tests.image.fake.FakeImageService()
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = '661122aa-1234-dede-fefe-babababababa'
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id)}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['name'], snapshot_name)
def test_snapshot_metadata_image(self):
expected_calls = [
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_PENDING_UPLOAD}},
{'args': (),
'kwargs':
{'task_state': task_states.IMAGE_UPLOADING,
'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]
func_call_matcher = matchers.FunctionCallMatcher(expected_calls)
self.flags(libvirt_snapshots_directory='./')
image_service = nova.tests.image.fake.FakeImageService()
test_instance = copy.deepcopy(self.test_instance)
test_instance["image_ref"] = 'a440c04b-79fa-479c-bed1-0b816eaec379'
instance_ref = db.instance_create(self.context, test_instance)
properties = {'instance_id': instance_ref['id'],
'user_id': str(self.context.user_id),
'architecture': 'fake_arch',
'key_a': 'value_a',
'key_b': 'value_b'}
snapshot_name = 'test-snap'
sent_meta = {'name': snapshot_name, 'is_public': False,
'status': 'creating', 'properties': properties}
recv_meta = image_service.create(context, sent_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.StubOutWithMock(libvirt_driver.utils, 'execute')
libvirt_driver.utils.execute = self.fake_execute
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.snapshot(self.context, instance_ref, recv_meta['id'],
func_call_matcher.call)
snapshot = image_service.show(context, recv_meta['id'])
self.assertIsNone(func_call_matcher.match())
self.assertEquals(snapshot['properties']['image_state'], 'available')
self.assertEquals(snapshot['properties']['architecture'], 'fake_arch')
self.assertEquals(snapshot['properties']['key_a'], 'value_a')
self.assertEquals(snapshot['properties']['key_b'], 'value_b')
self.assertEquals(snapshot['status'], 'active')
self.assertEquals(snapshot['name'], snapshot_name)
def test_attach_invalid_volume_type(self):
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.VolumeDriverNotFound,
conn.attach_volume,
{"driver_volume_type": "badtype"},
{"name": "fake-instance"},
"/dev/sda")
def test_multi_nic(self):
instance_data = dict(self.test_instance)
network_info = _fake_network_info(self.stubs, 2)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = db.instance_create(self.context, instance_data)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = conn.to_xml(instance_ref, network_info, disk_info)
tree = etree.fromstring(xml)
interfaces = tree.findall("./devices/interface")
self.assertEquals(len(interfaces), 2)
self.assertEquals(interfaces[0].get('type'), 'bridge')
def _check_xml_and_container(self, instance):
user_context = context.RequestContext(self.user_id,
self.project_id)
instance_ref = db.instance_create(user_context, instance)
self.flags(libvirt_type='lxc')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEquals(conn.uri(), 'lxc:///')
network_info = _fake_network_info(self.stubs, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = conn.to_xml(instance_ref, network_info, disk_info)
tree = etree.fromstring(xml)
check = [
(lambda t: t.find('.').get('type'), 'lxc'),
(lambda t: t.find('./os/type').text, 'exe'),
(lambda t: t.find('./devices/filesystem/target').get('dir'), '/')]
for i, (check, expected_result) in enumerate(check):
self.assertEqual(check(tree),
expected_result,
'%s failed common check %d' % (xml, i))
target = tree.find('./devices/filesystem/source').get('dir')
self.assertTrue(len(target) > 0)
def _check_xml_and_disk_prefix(self, instance, prefix=None):
user_context = context.RequestContext(self.user_id,
self.project_id)
instance_ref = db.instance_create(user_context, instance)
def _get_prefix(p, default):
if p:
return p + 'a'
return default
type_disk_map = {
'qemu': [
(lambda t: t.find('.').get('type'), 'qemu'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'vda'))],
'xen': [
(lambda t: t.find('.').get('type'), 'xen'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'sda'))],
'kvm': [
(lambda t: t.find('.').get('type'), 'kvm'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'vda'))],
'uml': [
(lambda t: t.find('.').get('type'), 'uml'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'ubda'))]
}
for (libvirt_type, checks) in type_disk_map.iteritems():
self.flags(libvirt_type=libvirt_type)
if prefix:
self.flags(libvirt_disk_prefix=prefix)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
network_info = _fake_network_info(self.stubs, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = conn.to_xml(instance_ref, network_info, disk_info)
tree = etree.fromstring(xml)
for i, (check, expected_result) in enumerate(checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed check %d' %
(check(tree), expected_result, i))
def _check_xml_and_disk_driver(self, image_meta):
os_open = os.open
directio_supported = True
def os_open_stub(path, flags, *args, **kwargs):
if flags & os.O_DIRECT:
if not directio_supported:
raise OSError(errno.EINVAL,
'%s: %s' % (os.strerror(errno.EINVAL), path))
flags &= ~os.O_DIRECT
return os_open(path, flags, *args, **kwargs)
self.stubs.Set(os, 'open', os_open_stub)
def connection_supports_direct_io_stub(*args, **kwargs):
return directio_supported
self.stubs.Set(libvirt_driver.LibvirtDriver,
'_supports_direct_io', connection_supports_direct_io_stub)
user_context = context.RequestContext(self.user_id, self.project_id)
instance_ref = db.instance_create(user_context, self.test_instance)
network_info = _fake_network_info(self.stubs, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = drv.to_xml(instance_ref, network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
disks = tree.findall('./devices/disk/driver')
for disk in disks:
self.assertEqual(disk.get("cache"), "none")
directio_supported = False
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = drv.to_xml(instance_ref, network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
disks = tree.findall('./devices/disk/driver')
for disk in disks:
self.assertEqual(disk.get("cache"), "writethrough")
def _check_xml_and_disk_bus(self, image_meta,
block_device_info, wantConfig):
user_context = context.RequestContext(self.user_id, self.project_id)
instance_ref = db.instance_create(user_context, self.test_instance)
network_info = _fake_network_info(self.stubs, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref,
block_device_info,
image_meta)
xml = drv.to_xml(instance_ref, network_info, disk_info, image_meta,
block_device_info=block_device_info)
tree = etree.fromstring(xml)
got_disks = tree.findall('./devices/disk')
got_disk_targets = tree.findall('./devices/disk/target')
for i in range(len(wantConfig)):
want_device_type = wantConfig[i][0]
want_device_bus = wantConfig[i][1]
want_device_dev = wantConfig[i][2]
got_device_type = got_disks[i].get('device')
got_device_bus = got_disk_targets[i].get('bus')
got_device_dev = got_disk_targets[i].get('dev')
self.assertEqual(got_device_type, want_device_type)
self.assertEqual(got_device_bus, want_device_bus)
self.assertEqual(got_device_dev, want_device_dev)
def _check_xml_and_uuid(self, image_meta):
user_context = context.RequestContext(self.user_id, self.project_id)
instance_ref = db.instance_create(user_context, self.test_instance)
network_info = _fake_network_info(self.stubs, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref)
xml = drv.to_xml(instance_ref, network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
self.assertEqual(tree.find('./uuid').text,
instance_ref['uuid'])
def _check_xml_and_uri(self, instance, expect_ramdisk, expect_kernel,
rescue=None, expect_xen_hvm=False, xen_only=False):
user_context = context.RequestContext(self.user_id, self.project_id)
instance_ref = db.instance_create(user_context, instance)
network_ref = db.project_get_networks(context.get_admin_context(),
self.project_id)[0]
type_uri_map = {'qemu': ('qemu:///system',
[(lambda t: t.find('.').get('type'), 'qemu'),
(lambda t: t.find('./os/type').text,
vm_mode.HVM),
(lambda t: t.find('./devices/emulator'), None)]),
'kvm': ('qemu:///system',
[(lambda t: t.find('.').get('type'), 'kvm'),
(lambda t: t.find('./os/type').text,
vm_mode.HVM),
(lambda t: t.find('./devices/emulator'), None)]),
'uml': ('uml:///system',
[(lambda t: t.find('.').get('type'), 'uml'),
(lambda t: t.find('./os/type').text,
vm_mode.UML)]),
'xen': ('xen:///',
[(lambda t: t.find('.').get('type'), 'xen'),
(lambda t: t.find('./os/type').text,
vm_mode.XEN)])}
if expect_xen_hvm or xen_only:
hypervisors_to_check = ['xen']
else:
hypervisors_to_check = ['qemu', 'kvm', 'xen']
if expect_xen_hvm:
type_uri_map = {}
type_uri_map['xen'] = ('xen:///',
[(lambda t: t.find('.').get('type'),
'xen'),
(lambda t: t.find('./os/type').text,
vm_mode.HVM)])
for hypervisor_type in hypervisors_to_check:
check_list = type_uri_map[hypervisor_type][1]
if rescue:
suffix = '.rescue'
else:
suffix = ''
if expect_kernel:
check = (lambda t: t.find('./os/kernel').text.split(
'/')[1], 'kernel' + suffix)
else:
check = (lambda t: t.find('./os/kernel'), None)
check_list.append(check)
if not expect_kernel and hypervisor_type in ['qemu', 'kvm']:
check = (lambda t: t.find('./os/root'), None)
check_list.append(check)
check = (lambda t: t.find('./os/cmdline'), None)
check_list.append(check)
if expect_ramdisk:
check = (lambda t: t.find('./os/initrd').text.split(
'/')[1], 'ramdisk' + suffix)
else:
check = (lambda t: t.find('./os/initrd'), None)
check_list.append(check)
if hypervisor_type in ['qemu', 'kvm']:
xpath = "./sysinfo/system/entry"
check = (lambda t: t.findall(xpath)[0].get("name"),
"manufacturer")
check_list.append(check)
check = (lambda t: t.findall(xpath)[0].text,
version.vendor_string())
check_list.append(check)
check = (lambda t: t.findall(xpath)[1].get("name"),
"product")
check_list.append(check)
check = (lambda t: t.findall(xpath)[1].text,
version.product_string())
check_list.append(check)
check = (lambda t: t.findall(xpath)[2].get("name"),
"version")
check_list.append(check)
# converted to None), so we need an `or ''` to correct for that
check = (lambda t: t.findall(xpath)[2].text or '',
version.version_string_with_package())
check_list.append(check)
check = (lambda t: t.findall(xpath)[3].get("name"),
"serial")
check_list.append(check)
check = (lambda t: t.findall(xpath)[3].text,
"cef19ce0-0ca2-11df-855d-b19fbce37686")
check_list.append(check)
check = (lambda t: t.findall(xpath)[4].get("name"),
"uuid")
check_list.append(check)
check = (lambda t: t.findall(xpath)[4].text,
instance['uuid'])
check_list.append(check)
if hypervisor_type in ['qemu', 'kvm']:
check = (lambda t: t.findall('./devices/serial')[0].get(
'type'), 'file')
check_list.append(check)
check = (lambda t: t.findall('./devices/serial')[1].get(
'type'), 'pty')
check_list.append(check)
check = (lambda t: t.findall('./devices/serial/source')[0].get(
'path').split('/')[1], 'console.log')
check_list.append(check)
else:
check = (lambda t: t.find('./devices/console').get(
'type'), 'pty')
check_list.append(check)
common_checks = [
(lambda t: t.find('.').tag, 'domain'),
(lambda t: t.find('./memory').text, '2097152')]
if rescue:
common_checks += [
(lambda t: t.findall('./devices/disk/source')[0].get(
'file').split('/')[1], 'disk.rescue'),
(lambda t: t.findall('./devices/disk/source')[1].get(
'file').split('/')[1], 'disk')]
else:
common_checks += [(lambda t: t.findall(
'./devices/disk/source')[0].get('file').split('/')[1],
'disk')]
common_checks += [(lambda t: t.findall(
'./devices/disk/source')[1].get('file').split('/')[1],
'disk.local')]
for (libvirt_type, (expected_uri, checks)) in type_uri_map.iteritems():
self.flags(libvirt_type=libvirt_type)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEquals(conn.uri(), expected_uri)
network_info = _fake_network_info(self.stubs, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance_ref,
rescue=rescue)
xml = conn.to_xml(instance_ref, network_info, disk_info,
rescue=rescue)
tree = etree.fromstring(xml)
for i, (check, expected_result) in enumerate(checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed check %d' %
(check(tree), expected_result, i))
for i, (check, expected_result) in enumerate(common_checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed common check %d' %
(check(tree), expected_result, i))
filterref = './devices/interface/filterref'
(network, mapping) = network_info[0]
nic_id = mapping['mac'].replace(':', '')
fw = firewall.NWFilterFirewall(fake.FakeVirtAPI(), conn)
instance_filter_name = fw._instance_filter_name(instance_ref,
nic_id)
self.assertEqual(tree.find(filterref).get('filter'),
instance_filter_name)
# This test is supposed to make sure we don't
testuri = 'something completely different'
self.flags(libvirt_uri=testuri)
for (libvirt_type, (expected_uri, checks)) in type_uri_map.iteritems():
self.flags(libvirt_type=libvirt_type)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEquals(conn.uri(), testuri)
db.instance_destroy(user_context, instance_ref['uuid'])
def test_ensure_filtering_rules_for_instance_timeout(self):
# ensure_filtering_fules_for_instance() finishes with timeout.
# Preparing mocks
def fake_none(self, *args):
return
def fake_raise(self):
raise libvirt.libvirtError('ERR')
class FakeTime(object):
def __init__(self):
self.counter = 0
def sleep(self, t):
self.counter += t
fake_timer = FakeTime()
# _fake_network_info must be called before create_fake_libvirt_mock(),
# as _fake_network_info calls importutils.import_class() and
# create_fake_libvirt_mock() mocks importutils.import_class().
network_info = _fake_network_info(self.stubs, 1)
self.create_fake_libvirt_mock()
instance_ref = db.instance_create(self.context, self.test_instance)
# Start test
self.mox.ReplayAll()
try:
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn.firewall_driver,
'setup_basic_filtering',
fake_none)
self.stubs.Set(conn.firewall_driver,
'prepare_instance_filter',
fake_none)
self.stubs.Set(conn.firewall_driver,
'instance_filter_exists',
fake_none)
conn.ensure_filtering_rules_for_instance(instance_ref,
network_info,
time_module=fake_timer)
except exception.NovaException, e:
msg = ('The firewall filter for %s does not exist' %
instance_ref['name'])
c1 = (0 <= str(e).find(msg))
self.assertTrue(c1)
self.assertEqual(29, fake_timer.counter, "Didn't wait the expected "
"amount of time")
db.instance_destroy(self.context, instance_ref['uuid'])
def test_check_can_live_migrate_dest_all_pass_with_block_migration(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest = "fake_host_2"
src = instance_ref['host']
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'disk_available_least': 400,
'cpu_info': 'asdf',
}
filename = "file"
self.mox.StubOutWithMock(conn, '_create_shared_storage_test_file')
self.mox.StubOutWithMock(conn, '_compare_cpu')
conn._compare_cpu("asdf")
conn._create_shared_storage_test_file().AndReturn(filename)
self.mox.ReplayAll()
return_value = conn.check_can_live_migrate_destination(self.context,
instance_ref, compute_info, compute_info, True)
self.assertThat({"filename": "file",
'disk_available_mb': 409600,
"disk_over_commit": False,
"block_migration": True},
matchers.DictMatches(return_value))
def test_check_can_live_migrate_dest_all_pass_no_block_migration(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest = "fake_host_2"
src = instance_ref['host']
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'cpu_info': 'asdf'}
filename = "file"
self.mox.StubOutWithMock(conn, '_create_shared_storage_test_file')
self.mox.StubOutWithMock(conn, '_compare_cpu')
conn._compare_cpu("asdf")
conn._create_shared_storage_test_file().AndReturn(filename)
self.mox.ReplayAll()
return_value = conn.check_can_live_migrate_destination(self.context,
instance_ref, compute_info, compute_info, False)
self.assertThat({"filename": "file",
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": None},
matchers.DictMatches(return_value))
def test_check_can_live_migrate_dest_incompatible_cpu_raises(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest = "fake_host_2"
src = instance_ref['host']
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'cpu_info': 'asdf'}
self.mox.StubOutWithMock(conn, '_compare_cpu')
conn._compare_cpu("asdf").AndRaise(exception.InvalidCPUInfo(
reason='foo')
)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidCPUInfo,
conn.check_can_live_migrate_destination,
self.context, instance_ref,
compute_info, compute_info, False)
def test_check_can_live_migrate_dest_cleanup_works_correctly(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": True,
"disk_over_commit": False,
"disk_available_mb": 1024}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, '_cleanup_shared_storage_test_file')
conn._cleanup_shared_storage_test_file("file")
self.mox.ReplayAll()
conn.check_can_live_migrate_destination_cleanup(self.context,
dest_check_data)
def test_check_can_live_migrate_source_works_correctly(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": True,
"disk_over_commit": False,
"disk_available_mb": 1024}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(False)
self.mox.StubOutWithMock(conn, "_assert_dest_node_has_enough_disk")
conn._assert_dest_node_has_enough_disk(self.context, instance_ref,
dest_check_data['disk_available_mb'],
False)
self.mox.ReplayAll()
conn.check_can_live_migrate_source(self.context, instance_ref,
dest_check_data)
def test_check_can_live_migrate_source_vol_backed_works_correctly(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": 1024,
"is_volume_backed": True}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(False)
self.mox.ReplayAll()
ret = conn.check_can_live_migrate_source(self.context, instance_ref,
dest_check_data)
self.assertTrue(type(ret) == dict)
self.assertTrue('is_shared_storage' in ret)
def test_check_can_live_migrate_source_vol_backed_fails(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": 1024,
"is_volume_backed": False}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(False)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidSharedStorage,
conn.check_can_live_migrate_source, self.context,
instance_ref, dest_check_data)
def test_check_can_live_migrate_dest_fail_shared_storage_with_blockm(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": True,
"disk_over_commit": False,
'disk_available_mb': 1024}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(True)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidLocalStorage,
conn.check_can_live_migrate_source,
self.context, instance_ref, dest_check_data)
def test_check_can_live_migrate_no_shared_storage_no_blck_mig_raises(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest_check_data = {"filename": "file",
"block_migration": False,
"disk_over_commit": False,
'disk_available_mb': 1024}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(False)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidSharedStorage,
conn.check_can_live_migrate_source,
self.context, instance_ref, dest_check_data)
def test_check_can_live_migrate_source_with_dest_not_enough_disk(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dest = "fake_host_2"
src = instance_ref['host']
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_check_shared_storage_test_file")
conn._check_shared_storage_test_file("file").AndReturn(False)
self.mox.StubOutWithMock(conn, "get_instance_disk_info")
conn.get_instance_disk_info(instance_ref["name"]).AndReturn(
'[{"virt_disk_size":2}]')
dest_check_data = {"filename": "file",
"disk_available_mb": 0,
"block_migration": True,
"disk_over_commit": False}
self.mox.ReplayAll()
self.assertRaises(exception.MigrationError,
conn.check_can_live_migrate_source,
self.context, instance_ref, dest_check_data)
def test_live_migration_raises_exception(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = {'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE}
instance_ref = db.instance_create(self.context, self.test_instance)
instance_ref = db.instance_update(self.context, instance_ref['uuid'],
instance_dict)
vdmock = self.mox.CreateMock(libvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "migrateToURI")
_bandwidth = CONF.live_migration_bandwidth
vdmock.migrateToURI(CONF.live_migration_uri % 'dest',
mox.IgnoreArg(),
None,
_bandwidth).AndRaise(libvirt.libvirtError('ERR'))
def fake_lookup(instance_name):
if instance_name == instance_ref['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
self.mox.StubOutWithMock(self.compute, "_rollback_live_migration")
self.compute._rollback_live_migration(self.context, instance_ref,
'dest', False)
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(libvirt.libvirtError,
conn._live_migration,
self.context, instance_ref, 'dest', False,
self.compute._rollback_live_migration)
instance_ref = db.instance_get(self.context, instance_ref['id'])
self.assertTrue(instance_ref['vm_state'] == vm_states.ACTIVE)
self.assertTrue(instance_ref['power_state'] == power_state.RUNNING)
db.instance_destroy(self.context, instance_ref['uuid'])
def test_pre_live_migration_works_correctly_mocked(self):
vol = {'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
class FakeNetworkInfo():
def fixed_ips(self):
return ["test_ip_addr"]
inst_ref = {'id': 'foo'}
c = context.get_admin_context()
nw_info = FakeNetworkInfo()
self.mox.StubOutWithMock(driver, "block_device_info_get_mapping")
driver.block_device_info_get_mapping(vol
).AndReturn(vol['block_device_mapping'])
self.mox.StubOutWithMock(conn, "volume_driver_method")
for v in vol['block_device_mapping']:
disk_info = {
'bus': "scsi",
'dev': v['mount_device'].rpartition("/")[2],
'type': "disk"
}
conn.volume_driver_method('connect_volume',
v['connection_info'],
disk_info)
self.mox.StubOutWithMock(conn, 'plug_vifs')
conn.plug_vifs(mox.IsA(inst_ref), nw_info)
self.mox.ReplayAll()
result = conn.pre_live_migration(c, inst_ref, vol, nw_info)
self.assertEqual(result, None)
def test_pre_live_migration_vol_backed_works_correctly_mocked(self):
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
vol = {'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
class FakeNetworkInfo():
def fixed_ips(self):
return ["test_ip_addr"]
inst_ref = db.instance_create(self.context, self.test_instance)
c = context.get_admin_context()
nw_info = FakeNetworkInfo()
self.mox.StubOutWithMock(conn, "volume_driver_method")
for v in vol['block_device_mapping']:
disk_info = {
'bus': "scsi",
'dev': v['mount_device'].rpartition("/")[2],
'type': "disk"
}
conn.volume_driver_method('connect_volume',
v['connection_info'],
disk_info)
self.mox.StubOutWithMock(conn, 'plug_vifs')
conn.plug_vifs(mox.IsA(inst_ref), nw_info)
self.mox.ReplayAll()
migrate_data = {'is_shared_storage': False,
'is_volume_backed': True,
'block_migration': False
}
ret = conn.pre_live_migration(c, inst_ref, vol, nw_info,
migrate_data)
self.assertEqual(ret, None)
self.assertTrue(os.path.exists('%s/%s/' % (tmpdir,
inst_ref['uuid'])))
db.instance_destroy(self.context, inst_ref['uuid'])
def test_pre_block_migration_works_correctly(self):
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = db.instance_create(self.context, self.test_instance)
dummy_info = [{'path': '%s/disk' % tmpdir,
'disk_size': 10737418240,
'type': 'raw',
'backing_file': ''},
{'backing_file': 'otherdisk_1234567',
'path': '%s/otherdisk' % tmpdir,
'virt_disk_size': 10737418240}]
dummyjson = json.dumps(dummy_info)
self.mox.StubOutWithMock(imagebackend.Image, 'cache')
imagebackend.Image.cache(context=mox.IgnoreArg(),
fetch_func=mox.IgnoreArg(),
filename='otherdisk',
image_id=self.test_instance['image_ref'],
project_id='fake',
size=10737418240L,
user_id=None).AndReturn(None)
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
conn.pre_block_migration(self.context, instance_ref,
dummyjson)
self.assertTrue(os.path.exists('%s/%s/' %
(tmpdir, instance_ref['uuid'])))
db.instance_destroy(self.context, instance_ref['uuid'])
def test_get_instance_disk_info_works_correctly(self):
instance_ref = db.instance_create(self.context, self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/test/disk.local'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"</devices></domain>")
vdmock = self.mox.CreateMock(libvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance_ref['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
GB = 1024 * 1024 * 1024
fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * GB
fake_libvirt_utils.disk_sizes['/test/disk.local'] = 20 * GB
fake_libvirt_utils.disk_backing_files['/test/disk.local'] = 'file'
self.mox.StubOutWithMock(os.path, "getsize")
os.path.getsize('/test/disk').AndReturn((10737418240))
os.path.getsize('/test/disk.local').AndReturn((3328599655))
ret = ("image: /test/disk\n"
"file format: raw\n"
"virtual size: 20G (21474836480 bytes)\n"
"disk size: 3.1G\n"
"cluster_size: 2097152\n"
"backing file: /test/dummy (actual path: /backing/file)\n")
self.mox.StubOutWithMock(os.path, "exists")
os.path.exists('/test/disk.local').AndReturn(True)
self.mox.StubOutWithMock(utils, "execute")
utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
'/test/disk.local').AndReturn((ret, ''))
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
info = conn.get_instance_disk_info(instance_ref['name'])
info = jsonutils.loads(info)
self.assertEquals(info[0]['type'], 'raw')
self.assertEquals(info[0]['path'], '/test/disk')
self.assertEquals(info[0]['disk_size'], 10737418240)
self.assertEquals(info[0]['backing_file'], "")
self.assertEquals(info[0]['over_committed_disk_size'], 0)
self.assertEquals(info[1]['type'], 'qcow2')
self.assertEquals(info[1]['path'], '/test/disk.local')
self.assertEquals(info[1]['virt_disk_size'], 21474836480)
self.assertEquals(info[1]['backing_file'], "file")
self.assertEquals(info[1]['over_committed_disk_size'], 18146236825)
db.instance_destroy(self.context, instance_ref['uuid'])
def test_spawn_with_network_info(self):
def fake_none(*args, **kwargs):
return
def fake_getLibVersion():
return 9007
def fake_getCapabilities():
return """
<capabilities>
<host>
<uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
<cpu>
<arch>x86_64</arch>
<model>Penryn</model>
<vendor>Intel</vendor>
<topology sockets='1' cores='2' threads='1'/>
<feature name='xtpr'/>
</cpu>
</host>
</capabilities>
"""
network_info = _fake_network_info(self.stubs, 1)
self.create_fake_libvirt_mock(getLibVersion=fake_getLibVersion,
getCapabilities=fake_getCapabilities)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance_type = db.instance_type_get(self.context,
instance_ref['instance_type_id'])
sys_meta = flavors.save_instance_type_info({}, instance_type)
instance_ref['system_metadata'] = sys_meta
instance = db.instance_create(self.context, instance_ref)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, 'get_info')
libvirt_driver.LibvirtDriver.get_info(instance
).AndReturn({'state': power_state.RUNNING})
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn.firewall_driver,
'setup_basic_filtering',
fake_none)
self.stubs.Set(conn.firewall_driver,
'prepare_instance_filter',
fake_none)
self.stubs.Set(imagebackend.Image,
'cache',
fake_none)
conn.spawn(self.context, instance, None, [], 'herp',
network_info=network_info)
path = os.path.join(CONF.instances_path, instance['name'])
if os.path.isdir(path):
shutil.rmtree(path)
path = os.path.join(CONF.instances_path, CONF.base_dir_name)
if os.path.isdir(path):
shutil.rmtree(os.path.join(CONF.instances_path,
CONF.base_dir_name))
def test_spawn_without_image_meta(self):
self.create_image_called = False
def fake_none(*args, **kwargs):
return
def fake_create_image(*args, **kwargs):
self.create_image_called = True
def fake_get_info(instance):
return {'state': power_state.RUNNING}
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance = db.instance_create(self.context, instance_ref)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, 'to_xml', fake_none)
self.stubs.Set(conn, '_create_image', fake_create_image)
self.stubs.Set(conn, '_create_domain_and_network', fake_none)
self.stubs.Set(conn, 'get_info', fake_get_info)
conn.spawn(self.context, instance, None, [], None)
self.assertTrue(self.create_image_called)
conn.spawn(self.context,
instance,
{'id': instance['image_ref']},
[],
None)
self.assertTrue(self.create_image_called)
def test_spawn_from_volume_calls_cache(self):
self.cache_called_for_disk = False
def fake_none(*args, **kwargs):
return
def fake_cache(*args, **kwargs):
if kwargs.get('image_id') == 'my_fake_image':
self.cache_called_for_disk = True
def fake_get_info(instance):
return {'state': power_state.RUNNING}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, 'to_xml', fake_none)
self.stubs.Set(imagebackend.Image, 'cache', fake_cache)
self.stubs.Set(conn, '_create_domain_and_network', fake_none)
self.stubs.Set(conn, 'get_info', fake_get_info)
block_device_info = {'root_device_name': '/dev/vda',
'block_device_mapping': [
{'mount_device': 'vda'}]}
instance_ref = self.test_instance
instance_ref['image_ref'] = ''
instance_ref['root_device_name'] = '/dev/vda'
instance = db.instance_create(self.context, instance_ref)
conn.spawn(self.context, instance, None, [], None,
block_device_info=block_device_info)
self.assertFalse(self.cache_called_for_disk)
db.instance_destroy(self.context, instance['uuid'])
instance_ref = self.test_instance
instance_ref['image_ref'] = 'my_fake_image'
instance_ref['root_device_name'] = '/dev/vda'
instance = db.instance_create(self.context, instance_ref)
conn.spawn(self.context, instance, None, [], None,
block_device_info=block_device_info)
self.assertFalse(self.cache_called_for_disk)
db.instance_destroy(self.context, instance['uuid'])
instance_ref['image_ref'] = 'my_fake_image'
instance = db.instance_create(self.context, instance_ref)
conn.spawn(self.context, instance, None, [], None)
self.assertTrue(self.cache_called_for_disk)
db.instance_destroy(self.context, instance['uuid'])
def test_create_image_plain(self):
gotFiles = []
def fake_image(self, instance, name, image_type=''):
class FakeImage(imagebackend.Image):
def __init__(self, instance, name):
self.path = os.path.join(instance['name'], name)
def create_image(self, prepare_template, base,
size, *args, **kwargs):
pass
def cache(self, fetch_func, filename, size=None,
*args, **kwargs):
gotFiles.append({'filename': filename,
'size': size})
def snapshot(self, name):
pass
return FakeImage(instance, name)
def fake_none(*args, **kwargs):
return
def fake_get_info(instance):
return {'state': power_state.RUNNING}
self.stubs.Set(nova.virt.libvirt.imagebackend.Backend, "image",
fake_image)
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance = db.instance_create(self.context, instance_ref)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, 'to_xml', fake_none)
self.stubs.Set(conn, '_create_domain_and_network', fake_none)
self.stubs.Set(conn, 'get_info', fake_get_info)
image_meta = {'id': instance['image_ref']}
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance,
None,
image_meta)
conn._create_image(context, instance,
disk_info['mapping'])
xml = conn.to_xml(instance, None,
disk_info, image_meta)
wantFiles = [
{'filename': '356a192b7913b04c54574d18c28d46e6395428ab',
'size': 10 * 1024 * 1024 * 1024},
{'filename': 'ephemeral_20_default',
'size': 20 * 1024 * 1024 * 1024},
]
self.assertEquals(gotFiles, wantFiles)
def test_create_image_with_swap(self):
gotFiles = []
def fake_image(self, instance, name, image_type=''):
class FakeImage(imagebackend.Image):
def __init__(self, instance, name):
self.path = os.path.join(instance['name'], name)
def create_image(self, prepare_template, base,
size, *args, **kwargs):
pass
def cache(self, fetch_func, filename, size=None,
*args, **kwargs):
gotFiles.append({'filename': filename,
'size': size})
def snapshot(self, name):
pass
return FakeImage(instance, name)
def fake_none(*args, **kwargs):
return
def fake_get_info(instance):
return {'state': power_state.RUNNING}
self.stubs.Set(nova.virt.libvirt.imagebackend.Backend, "image",
fake_image)
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance_ref['system_metadata']['instance_type_swap'] = 500
instance = db.instance_create(self.context, instance_ref)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, 'to_xml', fake_none)
self.stubs.Set(conn, '_create_domain_and_network', fake_none)
self.stubs.Set(conn, 'get_info', fake_get_info)
image_meta = {'id': instance['image_ref']}
disk_info = blockinfo.get_disk_info(CONF.libvirt_type,
instance,
None,
image_meta)
conn._create_image(context, instance,
disk_info['mapping'])
xml = conn.to_xml(instance, None,
disk_info, image_meta)
wantFiles = [
{'filename': '356a192b7913b04c54574d18c28d46e6395428ab',
'size': 10 * 1024 * 1024 * 1024},
{'filename': 'ephemeral_20_default',
'size': 20 * 1024 * 1024 * 1024},
{'filename': 'swap_500',
'size': 500 * 1024 * 1024},
]
self.assertEquals(gotFiles, wantFiles)
def test_get_console_output_file(self):
fake_libvirt_utils.files['console.log'] = '01234567890'
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance = db.instance_create(self.context, instance_ref)
console_dir = (os.path.join(tmpdir, instance['name']))
console_log = '%s/console.log' % (console_dir)
fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='file'>
<source path='%s'/>
<target port='0'/>
</console>
</devices>
</domain>
""" % console_log
def fake_lookup(id):
return FakeVirtDomain(fake_dom_xml)
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
try:
prev_max = libvirt_driver.MAX_CONSOLE_BYTES
libvirt_driver.MAX_CONSOLE_BYTES = 5
output = conn.get_console_output(instance)
finally:
libvirt_driver.MAX_CONSOLE_BYTES = prev_max
self.assertEquals('67890', output)
def test_get_console_output_pty(self):
fake_libvirt_utils.files['pty'] = '01234567890'
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance = db.instance_create(self.context, instance_ref)
console_dir = (os.path.join(tmpdir, instance['name']))
pty_file = '%s/fake_pty' % (console_dir)
fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='pty'>
<source path='%s'/>
<target port='0'/>
</console>
</devices>
</domain>
""" % pty_file
def fake_lookup(id):
return FakeVirtDomain(fake_dom_xml)
def _fake_flush(self, fake_pty):
return 'foo'
def _fake_append_to_file(self, data, fpath):
return 'pty'
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
libvirt_driver.LibvirtDriver._flush_libvirt_console = _fake_flush
libvirt_driver.LibvirtDriver._append_to_file = _fake_append_to_file
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
try:
prev_max = libvirt_driver.MAX_CONSOLE_BYTES
libvirt_driver.MAX_CONSOLE_BYTES = 5
output = conn.get_console_output(instance)
finally:
libvirt_driver.MAX_CONSOLE_BYTES = prev_max
self.assertEquals('67890', output)
def test_get_host_ip_addr(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ip = conn.get_host_ip_addr()
self.assertEquals(ip, CONF.my_ip)
def test_broken_connection(self):
for (error, domain) in (
(libvirt.VIR_ERR_SYSTEM_ERROR, libvirt.VIR_FROM_REMOTE),
(libvirt.VIR_ERR_SYSTEM_ERROR, libvirt.VIR_FROM_RPC),
(libvirt.VIR_ERR_INTERNAL_ERROR, libvirt.VIR_FROM_RPC)):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(conn, "_wrapped_conn")
self.mox.StubOutWithMock(conn._wrapped_conn, "getLibVersion")
self.mox.StubOutWithMock(libvirt.libvirtError, "get_error_code")
self.mox.StubOutWithMock(libvirt.libvirtError, "get_error_domain")
conn._wrapped_conn.getLibVersion().AndRaise(
libvirt.libvirtError("fake failure"))
libvirt.libvirtError.get_error_code().AndReturn(error)
libvirt.libvirtError.get_error_domain().AndReturn(domain)
self.mox.ReplayAll()
self.assertFalse(conn._test_connection())
self.mox.UnsetStubs()
def test_immediate_delete(self):
def fake_lookup_by_name(instance_name):
raise exception.InstanceNotFound(instance_id=instance_name)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
instance = db.instance_create(self.context, self.test_instance)
conn.destroy(instance, {})
def test_destroy_removes_disk(self):
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver,
'_undefine_domain')
libvirt_driver.LibvirtDriver._undefine_domain(instance)
self.mox.StubOutWithMock(shutil, "rmtree")
shutil.rmtree(os.path.join(CONF.instances_path, instance['name']))
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_cleanup_lvm')
libvirt_driver.LibvirtDriver._cleanup_lvm(instance)
self.mox.ReplayAll()
def fake_destroy(instance):
pass
def fake_os_path_exists(path):
return True
def fake_unplug_vifs(instance, network_info):
pass
def fake_unfilter_instance(instance, network_info):
pass
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_destroy', fake_destroy)
self.stubs.Set(conn, 'unplug_vifs', fake_unplug_vifs)
self.stubs.Set(conn.firewall_driver,
'unfilter_instance', fake_unfilter_instance)
self.stubs.Set(os.path, 'exists', fake_os_path_exists)
conn.destroy(instance, [])
def test_destroy_not_removes_disk(self):
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver,
'_undefine_domain')
libvirt_driver.LibvirtDriver._undefine_domain(instance)
self.mox.ReplayAll()
def fake_destroy(instance):
pass
def fake_os_path_exists(path):
return True
def fake_unplug_vifs(instance, network_info):
pass
def fake_unfilter_instance(instance, network_info):
pass
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_destroy', fake_destroy)
self.stubs.Set(conn, 'unplug_vifs', fake_unplug_vifs)
self.stubs.Set(conn.firewall_driver,
'unfilter_instance', fake_unfilter_instance)
self.stubs.Set(os.path, 'exists', fake_os_path_exists)
conn.destroy(instance, [], None, False)
def test_destroy_undefines(self):
mock = self.mox.CreateMock(libvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndReturn(1)
self.mox.ReplayAll()
def fake_lookup_by_name(instance_name):
return mock
def fake_get_info(instance_name):
return {'state': power_state.SHUTDOWN, 'id': -1}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
self.stubs.Set(conn, 'get_info', fake_get_info)
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
conn.destroy(instance, [])
def test_destroy_undefines_no_undefine_flags(self):
mock = self.mox.CreateMock(libvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(libvirt.libvirtError('Err'))
mock.undefine()
self.mox.ReplayAll()
def fake_lookup_by_name(instance_name):
return mock
def fake_get_info(instance_name):
return {'state': power_state.SHUTDOWN, 'id': -1}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
self.stubs.Set(conn, 'get_info', fake_get_info)
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
conn.destroy(instance, [])
def test_destroy_undefines_no_attribute_with_managed_save(self):
mock = self.mox.CreateMock(libvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(AttributeError())
mock.hasManagedSaveImage(0).AndReturn(True)
mock.managedSaveRemove(0)
mock.undefine()
self.mox.ReplayAll()
def fake_lookup_by_name(instance_name):
return mock
def fake_get_info(instance_name):
return {'state': power_state.SHUTDOWN, 'id': -1}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
self.stubs.Set(conn, 'get_info', fake_get_info)
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
conn.destroy(instance, [])
def test_destroy_undefines_no_attribute_no_managed_save(self):
mock = self.mox.CreateMock(libvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(AttributeError())
mock.hasManagedSaveImage(0).AndRaise(AttributeError())
mock.undefine()
self.mox.ReplayAll()
def fake_lookup_by_name(instance_name):
return mock
def fake_get_info(instance_name):
return {'state': power_state.SHUTDOWN, 'id': -1}
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
self.stubs.Set(conn, 'get_info', fake_get_info)
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
conn.destroy(instance, [])
def test_private_destroy_not_found(self):
mock = self.mox.CreateMock(libvirt.virDomain)
mock.ID()
mock.destroy()
self.mox.ReplayAll()
def fake_lookup_by_name(instance_name):
return mock
def fake_get_info(instance_name):
raise exception.InstanceNotFound(instance_id=instance_name)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(conn, '_lookup_by_name', fake_lookup_by_name)
self.stubs.Set(conn, 'get_info', fake_get_info)
instance = {"name": "instancename", "id": "instanceid",
"uuid": "875a8070-d0b9-4949-8b31-104d125c9a64"}
conn._destroy(instance)
def test_disk_over_committed_size_total(self):
# Ensure destroy calls managedSaveRemove for saved instance.
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
def list_instances():
return ['fake1', 'fake2']
self.stubs.Set(conn, 'list_instances', list_instances)
fake_disks = {'fake1': [{'type': 'qcow2', 'path': '/somepath/disk1',
'virt_disk_size': '10737418240',
'backing_file': '/somepath/disk1',
'disk_size': '83886080',
'over_committed_disk_size': '10653532160'}],
'fake2': [{'type': 'raw', 'path': '/somepath/disk2',
'virt_disk_size': '0',
'backing_file': '/somepath/disk2',
'disk_size': '10737418240',
'over_committed_disk_size': '0'}]}
def get_info(instance_name):
return jsonutils.dumps(fake_disks.get(instance_name))
self.stubs.Set(conn, 'get_instance_disk_info', get_info)
result = conn.get_disk_over_committed_size_total()
self.assertEqual(result, 10653532160)
def test_cpu_info(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigCPU()
cpu.model = "Opteron_G4"
cpu.vendor = "AMD"
cpu.arch = "x86_64"
cpu.cores = 2
cpu.threads = 1
cpu.sockets = 4
cpu.add_feature(vconfig.LibvirtConfigCPUFeature("extapic"))
cpu.add_feature(vconfig.LibvirtConfigCPUFeature("3dnow"))
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
guest = vconfig.LibvirtConfigGuest()
guest.ostype = vm_mode.HVM
guest.arch = "x86_64"
guest.domtype = ["kvm"]
caps.guests.append(guest)
guest = vconfig.LibvirtConfigGuest()
guest.ostype = vm_mode.HVM
guest.arch = "i686"
guest.domtype = ["kvm"]
caps.guests.append(guest)
return caps
self.stubs.Set(libvirt_driver.LibvirtDriver,
'get_host_capabilities',
get_host_capabilities_stub)
want = {"vendor": "AMD",
"features": ["extapic", "3dnow"],
"model": "Opteron_G4",
"arch": "x86_64",
"topology": {"cores": 2, "threads": 1, "sockets": 4}}
got = jsonutils.loads(conn.get_cpu_info())
self.assertEqual(want, got)
def test_diagnostic_vcpus_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
raise libvirt.libvirtError('vcpus missing')
def blockStats(self, path):
return (169L, 688640L, 0L, 0L, -1L)
def interfaceStats(self, path):
return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
def memoryStats(self):
return {'actual': 220160L, 'rss': 200164L}
def maxMemory(self):
return 280160L
def fake_lookup_name(name):
return DiagFakeDomain()
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actual = conn.get_diagnostics({"name": "testvirt"})
expect = {'vda_read': 688640L,
'vda_read_req': 169L,
'vda_write': 0L,
'vda_write_req': 0L,
'vda_errors': -1L,
'vdb_read': 688640L,
'vdb_read_req': 169L,
'vdb_write': 0L,
'vdb_write_req': 0L,
'vdb_errors': -1L,
'memory': 280160L,
'memory-actual': 220160L,
'memory-rss': 200164L,
'vnet0_rx': 4408L,
'vnet0_rx_drop': 0L,
'vnet0_rx_errors': 0L,
'vnet0_rx_packets': 82L,
'vnet0_tx': 0L,
'vnet0_tx_drop': 0L,
'vnet0_tx_errors': 0L,
'vnet0_tx_packets': 0L,
}
self.assertEqual(actual, expect)
def test_diagnostic_blockstats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000L, 0),
(1, 1, 1640000000L, 0),
(2, 1, 3040000000L, 0),
(3, 1, 1420000000L, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
raise libvirt.libvirtError('blockStats missing')
def interfaceStats(self, path):
return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
def memoryStats(self):
return {'actual': 220160L, 'rss': 200164L}
def maxMemory(self):
return 280160L
def fake_lookup_name(name):
return DiagFakeDomain()
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actual = conn.get_diagnostics({"name": "testvirt"})
expect = {'cpu0_time': 15340000000L,
'cpu1_time': 1640000000L,
'cpu2_time': 3040000000L,
'cpu3_time': 1420000000L,
'memory': 280160L,
'memory-actual': 220160L,
'memory-rss': 200164L,
'vnet0_rx': 4408L,
'vnet0_rx_drop': 0L,
'vnet0_rx_errors': 0L,
'vnet0_rx_packets': 82L,
'vnet0_tx': 0L,
'vnet0_tx_drop': 0L,
'vnet0_tx_errors': 0L,
'vnet0_tx_packets': 0L,
}
self.assertEqual(actual, expect)
def test_diagnostic_interfacestats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000L, 0),
(1, 1, 1640000000L, 0),
(2, 1, 3040000000L, 0),
(3, 1, 1420000000L, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169L, 688640L, 0L, 0L, -1L)
def interfaceStats(self, path):
raise libvirt.libvirtError('interfaceStat missing')
def memoryStats(self):
return {'actual': 220160L, 'rss': 200164L}
def maxMemory(self):
return 280160L
def fake_lookup_name(name):
return DiagFakeDomain()
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actual = conn.get_diagnostics({"name": "testvirt"})
expect = {'cpu0_time': 15340000000L,
'cpu1_time': 1640000000L,
'cpu2_time': 3040000000L,
'cpu3_time': 1420000000L,
'vda_read': 688640L,
'vda_read_req': 169L,
'vda_write': 0L,
'vda_write_req': 0L,
'vda_errors': -1L,
'vdb_read': 688640L,
'vdb_read_req': 169L,
'vdb_write': 0L,
'vdb_write_req': 0L,
'vdb_errors': -1L,
'memory': 280160L,
'memory-actual': 220160L,
'memory-rss': 200164L,
}
self.assertEqual(actual, expect)
def test_diagnostic_memorystats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000L, 0),
(1, 1, 1640000000L, 0),
(2, 1, 3040000000L, 0),
(3, 1, 1420000000L, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169L, 688640L, 0L, 0L, -1L)
def interfaceStats(self, path):
return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
def memoryStats(self):
raise libvirt.libvirtError('memoryStats missing')
def maxMemory(self):
return 280160L
def fake_lookup_name(name):
return DiagFakeDomain()
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actual = conn.get_diagnostics({"name": "testvirt"})
expect = {'cpu0_time': 15340000000L,
'cpu1_time': 1640000000L,
'cpu2_time': 3040000000L,
'cpu3_time': 1420000000L,
'vda_read': 688640L,
'vda_read_req': 169L,
'vda_write': 0L,
'vda_write_req': 0L,
'vda_errors': -1L,
'vdb_read': 688640L,
'vdb_read_req': 169L,
'vdb_write': 0L,
'vdb_write_req': 0L,
'vdb_errors': -1L,
'memory': 280160L,
'vnet0_rx': 4408L,
'vnet0_rx_drop': 0L,
'vnet0_rx_errors': 0L,
'vnet0_rx_packets': 82L,
'vnet0_tx': 0L,
'vnet0_tx_drop': 0L,
'vnet0_tx_errors': 0L,
'vnet0_tx_packets': 0L,
}
self.assertEqual(actual, expect)
def test_diagnostic_full(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000L, 0),
(1, 1, 1640000000L, 0),
(2, 1, 3040000000L, 0),
(3, 1, 1420000000L, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169L, 688640L, 0L, 0L, -1L)
def interfaceStats(self, path):
return (4408L, 82L, 0L, 0L, 0L, 0L, 0L, 0L)
def memoryStats(self):
return {'actual': 220160L, 'rss': 200164L}
def maxMemory(self):
return 280160L
def fake_lookup_name(name):
return DiagFakeDomain()
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actual = conn.get_diagnostics({"name": "testvirt"})
expect = {'cpu0_time': 15340000000L,
'cpu1_time': 1640000000L,
'cpu2_time': 3040000000L,
'cpu3_time': 1420000000L,
'vda_read': 688640L,
'vda_read_req': 169L,
'vda_write': 0L,
'vda_write_req': 0L,
'vda_errors': -1L,
'vdb_read': 688640L,
'vdb_read_req': 169L,
'vdb_write': 0L,
'vdb_write_req': 0L,
'vdb_errors': -1L,
'memory': 280160L,
'memory-actual': 220160L,
'memory-rss': 200164L,
'vnet0_rx': 4408L,
'vnet0_rx_drop': 0L,
'vnet0_rx_errors': 0L,
'vnet0_rx_packets': 82L,
'vnet0_tx': 0L,
'vnet0_tx_drop': 0L,
'vnet0_tx_errors': 0L,
'vnet0_tx_packets': 0L,
}
self.assertEqual(actual, expect)
def test_failing_vcpu_count(self):
"""Domain can fail to return the vcpu description in case it's
just starting up or shutting down. Make sure None is handled
gracefully.
"""
class DiagFakeDomain(object):
def __init__(self, vcpus):
self._vcpus = vcpus
def vcpus(self):
if self._vcpus is None:
return None
else:
return ([1] * self._vcpus, [True] * self._vcpus)
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conn = driver._conn
self.mox.StubOutWithMock(driver, 'list_instance_ids')
conn.lookupByID = self.mox.CreateMockAnything()
driver.list_instance_ids().AndReturn([1, 2])
conn.lookupByID(1).AndReturn(DiagFakeDomain(None))
conn.lookupByID(2).AndReturn(DiagFakeDomain(5))
self.mox.ReplayAll()
self.assertEqual(5, driver.get_vcpu_used())
def test_get_instance_capabilities(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
def get_host_capabilities_stub(self):
caps = vconfig.LibvirtConfigCaps()
guest = vconfig.LibvirtConfigGuest()
guest.ostype = 'hvm'
guest.arch = 'x86_64'
guest.domtype = ['kvm', 'qemu']
caps.guests.append(guest)
guest = vconfig.LibvirtConfigGuest()
guest.ostype = 'hvm'
guest.arch = 'i686'
guest.domtype = ['kvm']
caps.guests.append(guest)
return caps
self.stubs.Set(libvirt_driver.LibvirtDriver,
'get_host_capabilities',
get_host_capabilities_stub)
want = [('x86_64', 'kvm', 'hvm'),
('x86_64', 'qemu', 'hvm'),
('i686', 'kvm', 'hvm')]
got = conn.get_instance_capabilities()
self.assertEqual(want, got)
def test_event_dispatch(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
got_events = []
def handler(event):
got_events.append(event)
conn.register_event_listener(handler)
conn._init_events_pipe()
event1 = virtevent.LifecycleEvent(
"cef19ce0-0ca2-11df-855d-b19fbce37686",
virtevent.EVENT_LIFECYCLE_STARTED)
event2 = virtevent.LifecycleEvent(
"cef19ce0-0ca2-11df-855d-b19fbce37686",
virtevent.EVENT_LIFECYCLE_PAUSED)
conn._queue_event(event1)
conn._queue_event(event2)
conn._dispatch_events()
want_events = [event1, event2]
self.assertEqual(want_events, got_events)
event3 = virtevent.LifecycleEvent(
"cef19ce0-0ca2-11df-855d-b19fbce37686",
virtevent.EVENT_LIFECYCLE_RESUMED)
event4 = virtevent.LifecycleEvent(
"cef19ce0-0ca2-11df-855d-b19fbce37686",
virtevent.EVENT_LIFECYCLE_STOPPED)
conn._queue_event(event3)
conn._queue_event(event4)
conn._dispatch_events()
want_events = [event1, event2, event3, event4]
self.assertEqual(want_events, got_events)
def test_event_lifecycle(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
got_events = []
def handler(event):
got_events.append(event)
conn.register_event_listener(handler)
conn._init_events_pipe()
fake_dom_xml = """
<domain type='kvm'>
<uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
</devices>
</domain>
"""
dom = FakeVirtDomain(fake_dom_xml,
"cef19ce0-0ca2-11df-855d-b19fbce37686")
conn._event_lifecycle_callback(conn._conn,
dom,
libvirt.VIR_DOMAIN_EVENT_STOPPED,
0,
conn)
conn._dispatch_events()
self.assertEqual(len(got_events), 1)
self.assertEqual(type(got_events[0]), virtevent.LifecycleEvent)
self.assertEqual(got_events[0].uuid,
"cef19ce0-0ca2-11df-855d-b19fbce37686")
self.assertEqual(got_events[0].transition,
virtevent.EVENT_LIFECYCLE_STOPPED)
def test_set_cache_mode(self):
self.flags(disk_cachemodes=['file=directsync'])
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuestDisk()
fake_conf.source_type = 'file'
conn.set_cache_mode(fake_conf)
self.assertEqual(fake_conf.driver_cache, 'directsync')
def test_set_cache_mode_invalid_mode(self):
self.flags(disk_cachemodes=['file=FAKE'])
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuestDisk()
fake_conf.source_type = 'file'
conn.set_cache_mode(fake_conf)
self.assertEqual(fake_conf.driver_cache, None)
def test_set_cache_mode_invalid_object(self):
self.flags(disk_cachemodes=['file=directsync'])
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuest()
fake_conf.driver_cache = 'fake'
conn.set_cache_mode(fake_conf)
self.assertEqual(fake_conf.driver_cache, 'fake')
def _test_shared_storage_detection(self, is_same):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.mox.StubOutWithMock(conn, 'get_host_ip_addr')
self.mox.StubOutWithMock(utils, 'execute')
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(os, 'unlink')
conn.get_host_ip_addr().AndReturn('bar')
utils.execute('ssh', 'foo', 'touch', mox.IgnoreArg())
os.path.exists(mox.IgnoreArg()).AndReturn(is_same)
if is_same:
os.unlink(mox.IgnoreArg())
else:
utils.execute('ssh', 'foo', 'rm', mox.IgnoreArg())
self.mox.ReplayAll()
return conn._is_storage_shared_with('foo', '/path')
def test_shared_storage_detection_same_host(self):
self.assertTrue(self._test_shared_storage_detection(True))
def test_shared_storage_detection_different_host(self):
self.assertFalse(self._test_shared_storage_detection(False))
def test_shared_storage_detection_easy(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.mox.StubOutWithMock(conn, 'get_host_ip_addr')
self.mox.StubOutWithMock(utils, 'execute')
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(os, 'unlink')
conn.get_host_ip_addr().AndReturn('foo')
self.mox.ReplayAll()
self.assertTrue(conn._is_storage_shared_with('foo', '/path'))
class HostStateTestCase(test.TestCase):
cpu_info = ('{"vendor": "Intel", "model": "pentium", "arch": "i686", '
'"features": ["ssse3", "monitor", "pni", "sse2", "sse", '
'"fxsr", "clflush", "pse36", "pat", "cmov", "mca", "pge", '
'"mtrr", "sep", "apic"], '
'"topology": {"cores": "1", "threads": "1", "sockets": "1"}}')
instance_caps = [("x86_64", "kvm", "hvm"), ("i686", "kvm", "hvm")]
class FakeConnection(object):
"""Fake connection object."""
def get_vcpu_total(self):
return 1
def get_vcpu_used(self):
return 0
def get_cpu_info(self):
return HostStateTestCase.cpu_info
def get_local_gb_info(self):
return {'total': 100, 'used': 20, 'free': 80}
def get_memory_mb_total(self):
return 497
def get_memory_mb_used(self):
return 88
def get_hypervisor_type(self):
return 'QEMU'
def get_hypervisor_version(self):
return 13091
def get_hypervisor_hostname(self):
return 'compute1'
def get_host_uptime(self):
return ('10:01:16 up 1:36, 6 users, '
'load average: 0.21, 0.16, 0.19')
def get_disk_available_least(self):
return 13091
def get_instance_capabilities(self):
return HostStateTestCase.instance_caps
def test_update_status(self):
hs = libvirt_driver.HostState(self.FakeConnection())
stats = hs._stats
self.assertEquals(stats["vcpus"], 1)
self.assertEquals(stats["vcpus_used"], 0)
self.assertEquals(stats["cpu_info"],
{"vendor": "Intel", "model": "pentium", "arch": "i686",
"features": ["ssse3", "monitor", "pni", "sse2", "sse",
"fxsr", "clflush", "pse36", "pat", "cmov",
"mca", "pge", "mtrr", "sep", "apic"],
"topology": {"cores": "1", "threads": "1", "sockets": "1"}
})
self.assertEquals(stats["disk_total"], 100)
self.assertEquals(stats["disk_used"], 20)
self.assertEquals(stats["disk_available"], 80)
self.assertEquals(stats["host_memory_total"], 497)
self.assertEquals(stats["host_memory_free"], 409)
self.assertEquals(stats["hypervisor_type"], 'QEMU')
self.assertEquals(stats["hypervisor_version"], 13091)
self.assertEquals(stats["hypervisor_hostname"], 'compute1')
class NWFilterFakes:
def __init__(self):
self.filters = {}
def nwfilterLookupByName(self, name):
if name in self.filters:
return self.filters[name]
raise libvirt.libvirtError('Filter Not Found')
def filterDefineXMLMock(self, xml):
class FakeNWFilterInternal:
def __init__(self, parent, name, xml):
self.name = name
self.parent = parent
self.xml = xml
def undefine(self):
del self.parent.filters[self.name]
pass
tree = etree.fromstring(xml)
name = tree.get('name')
if name not in self.filters:
self.filters[name] = FakeNWFilterInternal(self, name, xml)
return True
class IptablesFirewallTestCase(test.TestCase):
def setUp(self):
super(IptablesFirewallTestCase, self).setUp()
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.RequestContext(self.user_id, self.project_id)
class FakeLibvirtDriver(object):
def nwfilterDefineXML(*args, **kwargs):
"""setup_basic_rules in nwfilter calls this."""
pass
self.fake_libvirt_connection = FakeLibvirtDriver()
self.fw = firewall.IptablesFirewallDriver(
fake.FakeVirtAPI(),
get_connection=lambda: self.fake_libvirt_connection)
in_rules = [
'# Generated by iptables-save v1.4.10 on Sat Feb 19 00:03:19 2011',
'*nat',
':PREROUTING ACCEPT [1170:189210]',
':INPUT ACCEPT [844:71028]',
':OUTPUT ACCEPT [5149:405186]',
':POSTROUTING ACCEPT [5063:386098]',
'# Completed on Tue Dec 18 15:50:25 2012',
'# Generated by iptables-save v1.4.12 on Tue Dec 18 15:50:25 201;',
'*mangle',
':PREROUTING ACCEPT [241:39722]',
':INPUT ACCEPT [230:39282]',
':FORWARD ACCEPT [0:0]',
':OUTPUT ACCEPT [266:26558]',
':POSTROUTING ACCEPT [267:26590]',
'-A POSTROUTING -o virbr0 -p udp -m udp --dport 68 -j CHECKSUM '
'--checksum-fill',
'COMMIT',
'# Completed on Tue Dec 18 15:50:25 2012',
'# Generated by iptables-save v1.4.4 on Mon Dec 6 11:54:13 2010',
'*filter',
':INPUT ACCEPT [969615:281627771]',
':FORWARD ACCEPT [0:0]',
':OUTPUT ACCEPT [915599:63811649]',
':nova-block-ipv4 - [0:0]',
'[0:0] -A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT ',
'[0:0] -A FORWARD -d 192.168.122.0/24 -o virbr0 -m state --state RELATED'
',ESTABLISHED -j ACCEPT ',
'[0:0] -A FORWARD -s 192.168.122.0/24 -i virbr0 -j ACCEPT ',
'[0:0] -A FORWARD -i virbr0 -o virbr0 -j ACCEPT ',
'[0:0] -A FORWARD -o virbr0 -j REJECT '
'--reject-with icmp-port-unreachable ',
'[0:0] -A FORWARD -i virbr0 -j REJECT '
'--reject-with icmp-port-unreachable ',
'COMMIT',
'# Completed on Mon Dec 6 11:54:13 2010',
]
in6_filter_rules = [
'# Generated by ip6tables-save v1.4.4 on Tue Jan 18 23:47:56 2011',
'*filter',
':INPUT ACCEPT [349155:75810423]',
':FORWARD ACCEPT [0:0]',
':OUTPUT ACCEPT [349256:75777230]',
'COMMIT',
'# Completed on Tue Jan 18 23:47:56 2011',
]
def _create_instance_ref(self):
return db.instance_create(self.context,
{'user_id': 'fake',
'project_id': 'fake',
'instance_type_id': 1})
def test_static_filters(self):
instance_ref = self._create_instance_ref()
src_instance_ref = self._create_instance_ref()
admin_ctxt = context.get_admin_context()
secgroup = db.security_group_create(admin_ctxt,
{'user_id': 'fake',
'project_id': 'fake',
'name': 'testgroup',
'description': 'test group'})
src_secgroup = db.security_group_create(admin_ctxt,
{'user_id': 'fake',
'project_id': 'fake',
'name': 'testsourcegroup',
'description': 'src group'})
db.security_group_rule_create(admin_ctxt,
{'parent_group_id': secgroup['id'],
'protocol': 'icmp',
'from_port': -1,
'to_port': -1,
'cidr': '192.168.11.0/24'})
db.security_group_rule_create(admin_ctxt,
{'parent_group_id': secgroup['id'],
'protocol': 'icmp',
'from_port': 8,
'to_port': -1,
'cidr': '192.168.11.0/24'})
db.security_group_rule_create(admin_ctxt,
{'parent_group_id': secgroup['id'],
'protocol': 'tcp',
'from_port': 80,
'to_port': 81,
'cidr': '192.168.10.0/24'})
db.security_group_rule_create(admin_ctxt,
{'parent_group_id': secgroup['id'],
'protocol': 'tcp',
'from_port': 80,
'to_port': 81,
'group_id': src_secgroup['id']})
db.security_group_rule_create(admin_ctxt,
{'parent_group_id': secgroup['id'],
'group_id': src_secgroup['id']})
db.instance_add_security_group(admin_ctxt, instance_ref['uuid'],
secgroup['id'])
db.instance_add_security_group(admin_ctxt, src_instance_ref['uuid'],
src_secgroup['id'])
instance_ref = db.instance_get(admin_ctxt, instance_ref['id'])
src_instance_ref = db.instance_get(admin_ctxt, src_instance_ref['id'])
def fake_iptables_execute(*cmd, **kwargs):
process_input = kwargs.get('process_input', None)
if cmd == ('ip6tables-save', '-c'):
return '\n'.join(self.in6_filter_rules), None
if cmd == ('iptables-save', '-c'):
return '\n'.join(self.in_rules), None
if cmd == ('iptables-restore', '-c'):
lines = process_input.split('\n')
if '*filter' in lines:
self.out_rules = lines
return '', ''
if cmd == ('ip6tables-restore', '-c',):
lines = process_input.split('\n')
if '*filter' in lines:
self.out6_rules = lines
return '', ''
network_model = _fake_network_info(self.stubs, 1, spectacular=True)
from nova.network import linux_net
linux_net.iptables_manager.execute = fake_iptables_execute
_fake_stub_out_get_nw_info(self.stubs, lambda *a, **kw: network_model)
network_info = network_model.legacy()
self.fw.prepare_instance_filter(instance_ref, network_info)
self.fw.apply_instance_filter(instance_ref, network_info)
in_rules = filter(lambda l: not l.startswith('#'),
self.in_rules)
for rule in in_rules:
if 'nova' not in rule:
self.assertTrue(rule in self.out_rules,
'Rule went missing: %s' % rule)
instance_chain = None
for rule in self.out_rules:
# last two octets change
if re.search('-d 192.168.[0-9]{1,3}.[0-9]{1,3} -j', rule):
instance_chain = rule.split(' ')[-1]
break
self.assertTrue(instance_chain, "The instance chain wasn't added")
security_group_chain = None
for rule in self.out_rules:
if '-A %s -j' % instance_chain in rule:
security_group_chain = rule.split(' ')[-1]
break
self.assertTrue(security_group_chain,
"The security group chain wasn't added")
regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p icmp '
'-s 192.168.11.0/24')
self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
"ICMP acceptance rule wasn't added")
regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p icmp -m icmp '
'--icmp-type 8 -s 192.168.11.0/24')
self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
"ICMP Echo Request acceptance rule wasn't added")
for ip in network_model.fixed_ips():
if ip['version'] != 4:
continue
regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p tcp -m multiport '
'--dports 80:81 -s %s' % ip['address'])
self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
"TCP port 80/81 acceptance rule wasn't added")
regex = re.compile('\[0\:0\] -A .* -j ACCEPT -s '
'%s' % ip['address'])
self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
"Protocol/port-less acceptance rule wasn't added")
regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p tcp '
'-m multiport --dports 80:81 -s 192.168.10.0/24')
self.assertTrue(len(filter(regex.match, self.out_rules)) > 0,
"TCP port 80/81 acceptance rule wasn't added")
db.instance_destroy(admin_ctxt, instance_ref['uuid'])
def test_filters_for_instance_with_ip_v6(self):
self.flags(use_ipv6=True)
network_info = _fake_network_info(self.stubs, 1)
rulesv4, rulesv6 = self.fw._filters_for_instance("fake", network_info)
self.assertEquals(len(rulesv4), 2)
self.assertEquals(len(rulesv6), 1)
def test_filters_for_instance_without_ip_v6(self):
self.flags(use_ipv6=False)
network_info = _fake_network_info(self.stubs, 1)
rulesv4, rulesv6 = self.fw._filters_for_instance("fake", network_info)
self.assertEquals(len(rulesv4), 2)
self.assertEquals(len(rulesv6), 0)
def test_multinic_iptables(self):
ipv4_rules_per_addr = 1
ipv4_addr_per_network = 2
ipv6_rules_per_addr = 1
ipv6_addr_per_network = 1
networks_count = 5
instance_ref = self._create_instance_ref()
network_info = _fake_network_info(self.stubs, networks_count,
ipv4_addr_per_network)
ipv4_len = len(self.fw.iptables.ipv4['filter'].rules)
ipv6_len = len(self.fw.iptables.ipv6['filter'].rules)
inst_ipv4, inst_ipv6 = self.fw.instance_rules(instance_ref,
network_info)
self.fw.prepare_instance_filter(instance_ref, network_info)
ipv4 = self.fw.iptables.ipv4['filter'].rules
ipv6 = self.fw.iptables.ipv6['filter'].rules
ipv4_network_rules = len(ipv4) - len(inst_ipv4) - ipv4_len
ipv6_network_rules = len(ipv6) - len(inst_ipv6) - ipv6_len
# Extra rules are for the DHCP request
rules = (ipv4_rules_per_addr * ipv4_addr_per_network *
networks_count) + 2
self.assertEquals(ipv4_network_rules, rules)
self.assertEquals(ipv6_network_rules,
ipv6_rules_per_addr * ipv6_addr_per_network * networks_count)
def test_do_refresh_security_group_rules(self):
instance_ref = self._create_instance_ref()
self.mox.StubOutWithMock(self.fw,
'instance_rules')
self.mox.StubOutWithMock(self.fw,
'add_filters_for_instance',
use_mock_anything=True)
self.fw.instance_rules(instance_ref,
mox.IgnoreArg()).AndReturn((None, None))
self.fw.add_filters_for_instance(instance_ref, mox.IgnoreArg(),
mox.IgnoreArg())
self.fw.instance_rules(instance_ref,
mox.IgnoreArg()).AndReturn((None, None))
self.fw.add_filters_for_instance(instance_ref, mox.IgnoreArg(),
mox.IgnoreArg())
self.mox.ReplayAll()
self.fw.prepare_instance_filter(instance_ref, mox.IgnoreArg())
self.fw.instances[instance_ref['id']] = instance_ref
self.fw.do_refresh_security_group_rules("fake")
def test_unfilter_instance_undefines_nwfilter(self):
admin_ctxt = context.get_admin_context()
fakefilter = NWFilterFakes()
_xml_mock = fakefilter.filterDefineXMLMock
self.fw.nwfilter._conn.nwfilterDefineXML = _xml_mock
_lookup_name = fakefilter.nwfilterLookupByName
self.fw.nwfilter._conn.nwfilterLookupByName = _lookup_name
instance_ref = self._create_instance_ref()
network_info = _fake_network_info(self.stubs, 1)
self.fw.setup_basic_filtering(instance_ref, network_info)
self.fw.prepare_instance_filter(instance_ref, network_info)
self.fw.apply_instance_filter(instance_ref, network_info)
original_filter_count = len(fakefilter.filters)
self.fw.unfilter_instance(instance_ref, network_info)
# should undefine just the instance filter
self.assertEqual(original_filter_count - len(fakefilter.filters), 1)
db.instance_destroy(admin_ctxt, instance_ref['uuid'])
def test_provider_firewall_rules(self):
# setup basic instance data
instance_ref = self._create_instance_ref()
# FRAGILE: peeks at how the firewall names chains
chain_name = 'inst-%s' % instance_ref['id']
# create a firewall via setup_basic_filtering like libvirt_conn.spawn
# should have a chain with 0 rules
network_info = _fake_network_info(self.stubs, 1)
self.fw.setup_basic_filtering(instance_ref, network_info)
self.assertTrue('provider' in self.fw.iptables.ipv4['filter'].chains)
rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules
if rule.chain == 'provider']
self.assertEqual(0, len(rules))
admin_ctxt = context.get_admin_context()
# add a rule and send the update message, check for 1 rule
provider_fw0 = db.provider_fw_rule_create(admin_ctxt,
{'protocol': 'tcp',
'cidr': '10.99.99.99/32',
'from_port': 1,
'to_port': 65535})
self.fw.refresh_provider_fw_rules()
rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules
if rule.chain == 'provider']
self.assertEqual(1, len(rules))
# Add another, refresh, and make sure number of rules goes to two
provider_fw1 = db.provider_fw_rule_create(admin_ctxt,
{'protocol': 'udp',
'cidr': '10.99.99.99/32',
'from_port': 1,
'to_port': 65535})
self.fw.refresh_provider_fw_rules()
rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules
if rule.chain == 'provider']
self.assertEqual(2, len(rules))
# create the instance filter and make sure it has a jump rule
self.fw.prepare_instance_filter(instance_ref, network_info)
self.fw.apply_instance_filter(instance_ref, network_info)
inst_rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules
if rule.chain == chain_name]
jump_rules = [rule for rule in inst_rules if '-j' in rule.rule]
provjump_rules = []
# IptablesTable doesn't make rules unique internally
for rule in jump_rules:
if 'provider' in rule.rule and rule not in provjump_rules:
provjump_rules.append(rule)
self.assertEqual(1, len(provjump_rules))
db.provider_fw_rule_destroy(admin_ctxt, provider_fw1['id'])
self.fw.refresh_provider_fw_rules()
rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules
if rule.chain == 'provider']
self.assertEqual(1, len(rules))
class NWFilterTestCase(test.TestCase):
def setUp(self):
super(NWFilterTestCase, self).setUp()
class Mock(object):
pass
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.RequestContext(self.user_id, self.project_id)
self.fake_libvirt_connection = Mock()
self.fw = firewall.NWFilterFirewall(fake.FakeVirtAPI(),
lambda: self.fake_libvirt_connection)
def test_cidr_rule_nwfilter_xml(self):
cloud_controller = cloud.CloudController()
cloud_controller.create_security_group(self.context,
'testgroup',
'test group description')
cloud_controller.authorize_security_group_ingress(self.context,
'testgroup',
from_port='80',
to_port='81',
ip_protocol='tcp',
cidr_ip='0.0.0.0/0')
security_group = db.security_group_get_by_name(self.context,
'fake',
'testgroup')
self.teardown_security_group()
def teardown_security_group(self):
cloud_controller = cloud.CloudController()
cloud_controller.delete_security_group(self.context, 'testgroup')
def setup_and_return_security_group(self):
cloud_controller = cloud.CloudController()
cloud_controller.create_security_group(self.context,
'testgroup',
'test group description')
cloud_controller.authorize_security_group_ingress(self.context,
'testgroup',
from_port='80',
to_port='81',
ip_protocol='tcp',
cidr_ip='0.0.0.0/0')
return db.security_group_get_by_name(self.context, 'fake', 'testgroup')
def _create_instance(self):
return db.instance_create(self.context,
{'user_id': 'fake',
'project_id': 'fake',
'instance_type_id': 1})
def _create_instance_type(self, params=None):
"""Create a test instance."""
if not params:
params = {}
context = self.context.elevated()
inst = {}
inst['name'] = 'm1.small'
inst['memory_mb'] = '1024'
inst['vcpus'] = '1'
inst['root_gb'] = '10'
inst['ephemeral_gb'] = '20'
inst['flavorid'] = '1'
inst['swap'] = '2048'
inst['rxtx_factor'] = 1
inst.update(params)
return db.instance_type_create(context, inst)['id']
def test_creates_base_rule_first(self):
self.defined_filters = ['no-mac-spoofing',
'no-ip-spoofing',
'no-arp-spoofing',
'allow-dhcp-server']
self.recursive_depends = {}
for f in self.defined_filters:
self.recursive_depends[f] = []
def _filterDefineXMLMock(xml):
dom = minidom.parseString(xml)
name = dom.firstChild.getAttribute('name')
self.recursive_depends[name] = []
for f in dom.getElementsByTagName('filterref'):
ref = f.getAttribute('filter')
self.assertTrue(ref in self.defined_filters,
('%s referenced filter that does ' +
'not yet exist: %s') % (name, ref))
dependencies = [ref] + self.recursive_depends[ref]
self.recursive_depends[name] += dependencies
self.defined_filters.append(name)
return True
self.fake_libvirt_connection.nwfilterDefineXML = _filterDefineXMLMock
instance_ref = self._create_instance()
inst_id = instance_ref['id']
inst_uuid = instance_ref['uuid']
def _ensure_all_called(mac, allow_dhcp):
instance_filter = 'nova-instance-%s-%s' % (instance_ref['name'],
mac.translate(None, ':'))
requiredlist = ['no-arp-spoofing', 'no-ip-spoofing',
'no-mac-spoofing']
if allow_dhcp:
requiredlist.append('allow-dhcp-server')
for required in requiredlist:
self.assertTrue(required in
self.recursive_depends[instance_filter],
"Instance's filter does not include %s" %
required)
self.security_group = self.setup_and_return_security_group()
db.instance_add_security_group(self.context, inst_uuid,
self.security_group['id'])
instance = db.instance_get(self.context, inst_id)
network_info = _fake_network_info(self.stubs, 1)
# since there is one (network_info) there is one vif
# pass this vif's mac to _ensure_all_called()
mac = network_info[0][1]['mac']
self.fw.setup_basic_filtering(instance, network_info)
allow_dhcp = False
for (network, mapping) in network_info:
if mapping['dhcp_server']:
allow_dhcp = True
break
_ensure_all_called(mac, allow_dhcp)
db.instance_remove_security_group(self.context, inst_uuid,
self.security_group['id'])
self.teardown_security_group()
db.instance_destroy(context.get_admin_context(), instance_ref['uuid'])
def test_unfilter_instance_undefines_nwfilters(self):
admin_ctxt = context.get_admin_context()
fakefilter = NWFilterFakes()
self.fw._conn.nwfilterDefineXML = fakefilter.filterDefineXMLMock
self.fw._conn.nwfilterLookupByName = fakefilter.nwfilterLookupByName
instance_ref = self._create_instance()
inst_id = instance_ref['id']
inst_uuid = instance_ref['uuid']
self.security_group = self.setup_and_return_security_group()
db.instance_add_security_group(self.context, inst_uuid,
self.security_group['id'])
instance = db.instance_get(self.context, inst_id)
network_info = _fake_network_info(self.stubs, 1)
self.fw.setup_basic_filtering(instance, network_info)
original_filter_count = len(fakefilter.filters)
self.fw.unfilter_instance(instance, network_info)
self.assertEqual(original_filter_count - len(fakefilter.filters), 1)
db.instance_destroy(admin_ctxt, instance_ref['uuid'])
def test_nwfilter_parameters(self):
admin_ctxt = context.get_admin_context()
fakefilter = NWFilterFakes()
self.fw._conn.nwfilterDefineXML = fakefilter.filterDefineXMLMock
self.fw._conn.nwfilterLookupByName = fakefilter.nwfilterLookupByName
instance_ref = self._create_instance()
inst_id = instance_ref['id']
inst_uuid = instance_ref['uuid']
self.security_group = self.setup_and_return_security_group()
db.instance_add_security_group(self.context, inst_uuid,
self.security_group['id'])
instance = db.instance_get(self.context, inst_id)
network_info = _fake_network_info(self.stubs, 1)
self.fw.setup_basic_filtering(instance, network_info)
(network, mapping) = network_info[0]
nic_id = mapping['mac'].replace(':', '')
instance_filter_name = self.fw._instance_filter_name(instance, nic_id)
f = fakefilter.nwfilterLookupByName(instance_filter_name)
tree = etree.fromstring(f.xml)
for fref in tree.findall('filterref'):
parameters = fref.findall('./parameter')
for parameter in parameters:
if parameter.get('name') == 'IP':
self.assertTrue(_ipv4_like(parameter.get('value'),
'192.168'))
elif parameter.get('name') == 'DHCPSERVER':
dhcp_server = mapping['dhcp_server']
self.assertEqual(parameter.get('value'), dhcp_server)
elif parameter.get('name') == 'RASERVER':
ra_server = mapping.get('gateway_v6') + "/128"
self.assertEqual(parameter.get('value'), ra_server)
elif parameter.get('name') == 'PROJNET':
ipv4_cidr = network['cidr']
net, mask = netutils.get_net_and_mask(ipv4_cidr)
self.assertEqual(parameter.get('value'), net)
elif parameter.get('name') == 'PROJMASK':
ipv4_cidr = network['cidr']
net, mask = netutils.get_net_and_mask(ipv4_cidr)
self.assertEqual(parameter.get('value'), mask)
elif parameter.get('name') == 'PROJNET6':
ipv6_cidr = network['cidr_v6']
net, prefix = netutils.get_net_and_prefixlen(ipv6_cidr)
self.assertEqual(parameter.get('value'), net)
elif parameter.get('name') == 'PROJMASK6':
ipv6_cidr = network['cidr_v6']
net, prefix = netutils.get_net_and_prefixlen(ipv6_cidr)
self.assertEqual(parameter.get('value'), prefix)
else:
raise exception.InvalidParameterValue('unknown parameter '
'in filter')
db.instance_destroy(admin_ctxt, instance_ref['uuid'])
class LibvirtUtilsTestCase(test.TestCase):
def test_get_iscsi_initiator(self):
self.mox.StubOutWithMock(utils, 'execute')
initiator = 'fake.initiator.iqn'
rval = ("junk\nInitiatorName=%s\njunk\n" % initiator, None)
utils.execute('cat', '/etc/iscsi/initiatorname.iscsi',
run_as_root=True).AndReturn(rval)
self.mox.ReplayAll()
result = libvirt_utils.get_iscsi_initiator()
self.assertEqual(initiator, result)
def test_create_image(self):
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('qemu-img', 'create', '-f', 'raw',
'/some/path', '10G')
utils.execute('qemu-img', 'create', '-f', 'qcow2',
'/some/stuff', '1234567891234')
self.mox.ReplayAll()
libvirt_utils.create_image('raw', '/some/path', '10G')
libvirt_utils.create_image('qcow2', '/some/stuff', '1234567891234')
def test_create_cow_image(self):
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(utils, 'execute')
rval = ('', '')
os.path.exists('/some/path').AndReturn(True)
utils.execute('env', 'LC_ALL=C', 'LANG=C',
'qemu-img', 'info', '/some/path').AndReturn(rval)
utils.execute('qemu-img', 'create', '-f', 'qcow2',
'-o', 'backing_file=/some/path',
'/the/new/cow')
self.mox.ReplayAll()
libvirt_utils.create_cow_image('/some/path', '/the/new/cow')
def test_pick_disk_driver_name(self):
type_map = {'kvm': ([True, 'qemu'], [False, 'qemu'], [None, 'qemu']),
'qemu': ([True, 'qemu'], [False, 'qemu'], [None, 'qemu']),
'xen': ([True, 'phy'], [False, 'tap'], [None, 'tap']),
'uml': ([True, None], [False, None], [None, None]),
'lxc': ([True, None], [False, None], [None, None])}
for (libvirt_type, checks) in type_map.iteritems():
self.flags(libvirt_type=libvirt_type)
for (is_block_dev, expected_result) in checks:
result = libvirt_utils.pick_disk_driver_name(is_block_dev)
self.assertEquals(result, expected_result)
def test_get_disk_size(self):
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(utils, 'execute')
os.path.exists('/some/path').AndReturn(True)
utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
'/some/path').AndReturn(('''image: 00000001
file format: raw
virtual size: 4.4M (4592640 bytes)
disk size: 4.4M''', ''))
self.mox.ReplayAll()
self.assertEquals(disk.get_disk_size('/some/path'), 4592640)
def test_copy_image(self):
dst_fd, dst_path = tempfile.mkstemp()
try:
os.close(dst_fd)
src_fd, src_path = tempfile.mkstemp()
try:
with os.fdopen(src_fd, 'w') as fp:
fp.write('canary')
libvirt_utils.copy_image(src_path, dst_path)
with open(dst_path, 'r') as fp:
self.assertEquals(fp.read(), 'canary')
finally:
os.unlink(src_path)
finally:
os.unlink(dst_path)
def test_write_to_file(self):
dst_fd, dst_path = tempfile.mkstemp()
try:
os.close(dst_fd)
libvirt_utils.write_to_file(dst_path, 'hello')
with open(dst_path, 'r') as fp:
self.assertEquals(fp.read(), 'hello')
finally:
os.unlink(dst_path)
def test_write_to_file_with_umask(self):
dst_fd, dst_path = tempfile.mkstemp()
try:
os.close(dst_fd)
os.unlink(dst_path)
libvirt_utils.write_to_file(dst_path, 'hello', umask=0277)
with open(dst_path, 'r') as fp:
self.assertEquals(fp.read(), 'hello')
mode = os.stat(dst_path).st_mode
self.assertEquals(mode & 0277, 0)
finally:
os.unlink(dst_path)
def test_chown(self):
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('chown', 'soren', '/some/path', run_as_root=True)
self.mox.ReplayAll()
libvirt_utils.chown('/some/path', 'soren')
def _do_test_extract_snapshot(self, dest_format='raw', out_format='raw'):
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('qemu-img', 'convert', '-f', 'qcow2', '-O', out_format,
'-s', 'snap1', '/path/to/disk/image', '/extracted/snap')
self.mox.ReplayAll()
libvirt_utils.extract_snapshot('/path/to/disk/image', 'qcow2',
'snap1', '/extracted/snap', dest_format)
def test_extract_snapshot_raw(self):
self._do_test_extract_snapshot()
def test_extract_snapshot_iso(self):
self._do_test_extract_snapshot(dest_format='iso')
def test_extract_snapshot_qcow2(self):
self._do_test_extract_snapshot(dest_format='qcow2', out_format='qcow2')
def test_load_file(self):
dst_fd, dst_path = tempfile.mkstemp()
try:
os.close(dst_fd)
libvirt_utils.write_to_file(dst_path, 'hello')
self.assertEquals(libvirt_utils.load_file(dst_path), 'hello')
finally:
os.unlink(dst_path)
def test_file_open(self):
dst_fd, dst_path = tempfile.mkstemp()
try:
os.close(dst_fd)
libvirt_utils.write_to_file(dst_path, 'hello')
with libvirt_utils.file_open(dst_path, 'r') as fp:
self.assertEquals(fp.read(), 'hello')
finally:
os.unlink(dst_path)
def test_get_fs_info(self):
class FakeStatResult(object):
def __init__(self):
self.f_bsize = 4096
self.f_frsize = 4096
self.f_blocks = 2000
self.f_bfree = 1000
self.f_bavail = 900
self.f_files = 2000
self.f_ffree = 1000
self.f_favail = 900
self.f_flag = 4096
self.f_namemax = 255
self.path = None
def fake_statvfs(path):
self.path = path
return FakeStatResult()
self.stubs.Set(os, 'statvfs', fake_statvfs)
fs_info = libvirt_utils.get_fs_info('/some/file/path')
self.assertEquals('/some/file/path', self.path)
self.assertEquals(8192000, fs_info['total'])
self.assertEquals(3686400, fs_info['free'])
self.assertEquals(4096000, fs_info['used'])
def test_fetch_image(self):
self.mox.StubOutWithMock(images, 'fetch_to_raw')
context = 'opaque context'
target = '/tmp/targetfile'
image_id = '4'
user_id = 'fake'
project_id = 'fake'
images.fetch_to_raw(context, image_id, target, user_id, project_id)
self.mox.ReplayAll()
libvirt_utils.fetch_image(context, target, image_id,
user_id, project_id)
def test_fetch_raw_image(self):
def fake_execute(*cmd, **kwargs):
self.executes.append(cmd)
return None, None
def fake_rename(old, new):
self.executes.append(('mv', old, new))
def fake_unlink(path):
self.executes.append(('rm', path))
def fake_rm_on_errror(path):
self.executes.append(('rm', '-f', path))
def fake_qemu_img_info(path):
class FakeImgInfo(object):
pass
file_format = path.split('.')[-1]
if file_format == 'part':
file_format = path.split('.')[-2]
elif file_format == 'converted':
file_format = 'raw'
if 'backing' in path:
backing_file = 'backing'
else:
backing_file = None
FakeImgInfo.file_format = file_format
FakeImgInfo.backing_file = backing_file
return FakeImgInfo()
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(os, 'rename', fake_rename)
self.stubs.Set(os, 'unlink', fake_unlink)
self.stubs.Set(images, 'fetch', lambda *_: None)
self.stubs.Set(images, 'qemu_img_info', fake_qemu_img_info)
self.stubs.Set(utils, 'delete_if_exists', fake_rm_on_errror)
context = 'opaque context'
image_id = '4'
user_id = 'fake'
project_id = 'fake'
target = 't.qcow2'
self.executes = []
expected_commands = [('qemu-img', 'convert', '-O', 'raw',
't.qcow2.part', 't.qcow2.converted'),
('rm', 't.qcow2.part'),
('mv', 't.qcow2.converted', 't.qcow2')]
images.fetch_to_raw(context, image_id, target, user_id, project_id)
self.assertEqual(self.executes, expected_commands)
target = 't.raw'
self.executes = []
expected_commands = [('mv', 't.raw.part', 't.raw')]
images.fetch_to_raw(context, image_id, target, user_id, project_id)
self.assertEqual(self.executes, expected_commands)
target = 'backing.qcow2'
self.executes = []
expected_commands = [('rm', '-f', 'backing.qcow2.part')]
self.assertRaises(exception.ImageUnacceptable,
images.fetch_to_raw,
context, image_id, target, user_id, project_id)
self.assertEqual(self.executes, expected_commands)
del self.executes
def test_get_disk_backing_file(self):
with_actual_path = False
def fake_execute(*args, **kwargs):
if with_actual_path:
return ("some: output\n"
"backing file: /foo/bar/baz (actual path: /a/b/c)\n"
"...: ...\n"), ''
else:
return ("some: output\n"
"backing file: /foo/bar/baz\n"
"...: ...\n"), ''
def return_true(*args, **kwargs):
return True
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(os.path, 'exists', return_true)
out = libvirt_utils.get_disk_backing_file('')
self.assertEqual(out, 'baz')
with_actual_path = True
out = libvirt_utils.get_disk_backing_file('')
self.assertEqual(out, 'c')
class LibvirtDriverTestCase(test.TestCase):
"""Test for nova.virt.libvirt.libvirt_driver.LibvirtDriver."""
def setUp(self):
super(LibvirtDriverTestCase, self).setUp()
self.libvirtconnection = libvirt_driver.LibvirtDriver(
fake.FakeVirtAPI(), read_only=True)
def _create_instance(self, params=None):
"""Create a test instance."""
if not params:
params = {}
sys_meta = flavors.save_instance_type_info(
{}, flavors.get_instance_type_by_name('m1.tiny'))
inst = {}
inst['image_ref'] = '1'
inst['reservation_id'] = 'r-fakeres'
inst['launch_time'] = '10'
inst['user_id'] = 'fake'
inst['project_id'] = 'fake'
type_id = flavors.get_instance_type_by_name('m1.tiny')['id']
inst['instance_type_id'] = type_id
inst['ami_launch_index'] = 0
inst['host'] = 'host1'
inst['root_gb'] = 10
inst['ephemeral_gb'] = 20
inst['config_drive'] = 1
inst['kernel_id'] = 2
inst['ramdisk_id'] = 3
inst['config_drive_id'] = 1
inst['key_data'] = 'ABCDEFG'
inst['system_metadata'] = sys_meta
inst.update(params)
return db.instance_create(context.get_admin_context(), inst)
def test_migrate_disk_and_power_off_exception(self):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.migrate_disk_and_power_off. """
self.counter = 0
self.checked_shared_storage = False
def fake_get_instance_disk_info(instance, xml=None):
return '[]'
def fake_destroy(instance):
pass
def fake_get_host_ip_addr():
return '10.0.0.1'
def fake_execute(*args, **kwargs):
self.counter += 1
if self.counter == 1:
assert False, "intentional failure"
def fake_os_path_exists(path):
return True
def fake_is_storage_shared(dest, inst_base):
self.checked_shared_storage = True
return False
self.stubs.Set(self.libvirtconnection, 'get_instance_disk_info',
fake_get_instance_disk_info)
self.stubs.Set(self.libvirtconnection, '_destroy', fake_destroy)
self.stubs.Set(self.libvirtconnection, 'get_host_ip_addr',
fake_get_host_ip_addr)
self.stubs.Set(self.libvirtconnection, '_is_storage_shared_with',
fake_is_storage_shared)
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(os.path, 'exists', fake_os_path_exists)
ins_ref = self._create_instance()
self.assertRaises(AssertionError,
self.libvirtconnection.migrate_disk_and_power_off,
None, ins_ref, '10.0.0.2', None, None)
def test_migrate_disk_and_power_off(self):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.migrate_disk_and_power_off. """
disk_info = [{'type': 'qcow2', 'path': '/test/disk',
'virt_disk_size': '10737418240',
'backing_file': '/base/disk',
'disk_size': '83886080'},
{'type': 'raw', 'path': '/test/disk.local',
'virt_disk_size': '10737418240',
'backing_file': '/base/disk.local',
'disk_size': '83886080'}]
disk_info_text = jsonutils.dumps(disk_info)
def fake_get_instance_disk_info(instance, xml=None):
return disk_info_text
def fake_destroy(instance):
pass
def fake_get_host_ip_addr():
return '10.0.0.1'
def fake_execute(*args, **kwargs):
pass
self.stubs.Set(self.libvirtconnection, 'get_instance_disk_info',
fake_get_instance_disk_info)
self.stubs.Set(self.libvirtconnection, '_destroy', fake_destroy)
self.stubs.Set(self.libvirtconnection, 'get_host_ip_addr',
fake_get_host_ip_addr)
self.stubs.Set(utils, 'execute', fake_execute)
ins_ref = self._create_instance()
out = self.libvirtconnection.migrate_disk_and_power_off(
None, ins_ref, '10.0.0.2', None, None)
self.assertEquals(out, disk_info_text)
out = self.libvirtconnection.migrate_disk_and_power_off(
None, ins_ref, '10.0.0.1', None, None)
self.assertEquals(out, disk_info_text)
def test_wait_for_running(self):
def fake_get_info(instance):
if instance['name'] == "not_found":
raise exception.NotFound
elif instance['name'] == "running":
return {'state': power_state.RUNNING}
else:
return {'state': power_state.SHUTDOWN}
self.stubs.Set(self.libvirtconnection, 'get_info',
fake_get_info)
self.assertRaises(exception.NotFound,
self.libvirtconnection._wait_for_running,
{'name': 'not_found',
'uuid': 'not_found_uuid'})
self.assertRaises(loopingcall.LoopingCallDone,
self.libvirtconnection._wait_for_running,
{'name': 'running',
'uuid': 'running_uuid'})
self.libvirtconnection._wait_for_running({'name': 'else',
'uuid': 'other_uuid'})
def test_finish_migration(self):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.finish_migration. """
disk_info = [{'type': 'qcow2', 'path': '/test/disk',
'local_gb': 10, 'backing_file': '/base/disk'},
{'type': 'raw', 'path': '/test/disk.local',
'local_gb': 10, 'backing_file': '/base/disk.local'}]
disk_info_text = jsonutils.dumps(disk_info)
def fake_can_resize_fs(path, size, use_cow=False):
return False
def fake_extend(path, size):
pass
def fake_to_xml(instance, network_info, disk_info,
image_meta=None, rescue=None,
block_device_info=None, write_to_disk=False):
return ""
def fake_plug_vifs(instance, network_info):
pass
def fake_create_image(context, inst,
disk_mapping, suffix='',
disk_images=None, network_info=None,
block_device_info=None):
pass
def fake_create_domain(xml, instance=None):
return None
def fake_enable_hairpin(instance):
pass
def fake_execute(*args, **kwargs):
pass
def fake_get_info(instance):
return {'state': power_state.RUNNING}
self.flags(use_cow_images=True)
self.stubs.Set(libvirt_driver.disk, 'extend', fake_extend)
self.stubs.Set(libvirt_driver.disk, 'can_resize_fs',
fake_can_resize_fs)
self.stubs.Set(self.libvirtconnection, 'to_xml', fake_to_xml)
self.stubs.Set(self.libvirtconnection, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(self.libvirtconnection, '_create_image',
fake_create_image)
self.stubs.Set(self.libvirtconnection, '_create_domain',
fake_create_domain)
self.stubs.Set(self.libvirtconnection, '_enable_hairpin',
fake_enable_hairpin)
self.stubs.Set(utils, 'execute', fake_execute)
fw = base_firewall.NoopFirewallDriver()
self.stubs.Set(self.libvirtconnection, 'firewall_driver', fw)
self.stubs.Set(self.libvirtconnection, 'get_info',
fake_get_info)
ins_ref = self._create_instance()
self.libvirtconnection.finish_migration(
context.get_admin_context(), None, ins_ref,
disk_info_text, None, None, None)
def test_finish_revert_migration(self):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.finish_revert_migration. """
def fake_execute(*args, **kwargs):
pass
def fake_plug_vifs(instance, network_info):
pass
def fake_create_domain(xml, instance=None):
return None
def fake_enable_hairpin(instance):
pass
def fake_get_info(instance):
return {'state': power_state.RUNNING}
def fake_to_xml(instance, network_info, disk_info,
image_meta=None, rescue=None,
block_device_info=None):
return ""
self.stubs.Set(self.libvirtconnection, 'to_xml', fake_to_xml)
self.stubs.Set(self.libvirtconnection, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(utils, 'execute', fake_execute)
fw = base_firewall.NoopFirewallDriver()
self.stubs.Set(self.libvirtconnection, 'firewall_driver', fw)
self.stubs.Set(self.libvirtconnection, '_create_domain',
fake_create_domain)
self.stubs.Set(self.libvirtconnection, '_enable_hairpin',
fake_enable_hairpin)
self.stubs.Set(self.libvirtconnection, 'get_info',
fake_get_info)
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
ins_ref = self._create_instance()
os.mkdir(os.path.join(tmpdir, ins_ref['name']))
libvirt_xml_path = os.path.join(tmpdir,
ins_ref['name'],
'libvirt.xml')
f = open(libvirt_xml_path, 'w')
f.close()
self.libvirtconnection.finish_revert_migration(ins_ref, None)
def _test_finish_revert_migration_after_crash(self, backup_made, new_made):
class FakeLoopingCall:
def start(self, *a, **k):
return self
def wait(self):
return None
self.mox.StubOutWithMock(libvirt_utils, 'get_instance_path')
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(shutil, 'rmtree')
self.mox.StubOutWithMock(utils, 'execute')
self.stubs.Set(blockinfo, 'get_disk_info', lambda *a: None)
self.stubs.Set(self.libvirtconnection, 'to_xml', lambda *a, **k: None)
self.stubs.Set(self.libvirtconnection, '_create_domain_and_network',
lambda *a: None)
self.stubs.Set(loopingcall, 'FixedIntervalLoopingCall',
lambda *a, **k: FakeLoopingCall())
libvirt_utils.get_instance_path({}).AndReturn('/fake/foo')
os.path.exists('/fake/foo_resize').AndReturn(backup_made)
if backup_made:
os.path.exists('/fake/foo').AndReturn(new_made)
if new_made:
shutil.rmtree('/fake/foo')
utils.execute('mv', '/fake/foo_resize', '/fake/foo')
self.mox.ReplayAll()
self.libvirtconnection.finish_revert_migration({}, [])
def test_finish_revert_migration_after_crash(self):
self._test_finish_revert_migration_after_crash(True, True)
def test_finish_revert_migration_after_crash_before_new(self):
self._test_finish_revert_migration_after_crash(True, False)
def test_finish_revert_migration_after_crash_before_backup(self):
self._test_finish_revert_migration_after_crash(False, False)
def test_cleanup_failed_migration(self):
self.mox.StubOutWithMock(shutil, 'rmtree')
shutil.rmtree('/fake/inst')
self.mox.ReplayAll()
self.libvirtconnection._cleanup_failed_migration('/fake/inst')
def test_confirm_migration(self):
ins_ref = self._create_instance()
self.mox.StubOutWithMock(self.libvirtconnection, "_cleanup_resize")
self.libvirtconnection._cleanup_resize(ins_ref,
_fake_network_info(self.stubs, 1))
self.mox.ReplayAll()
self.libvirtconnection.confirm_migration("migration_ref", ins_ref,
_fake_network_info(self.stubs, 1))
def test_cleanup_resize_same_host(self):
ins_ref = self._create_instance({'host': CONF.host})
def fake_os_path_exists(path):
return True
def fake_shutil_rmtree(target):
pass
self.stubs.Set(os.path, 'exists', fake_os_path_exists)
self.stubs.Set(shutil, 'rmtree', fake_shutil_rmtree)
self.mox.ReplayAll()
self.libvirtconnection._cleanup_resize(ins_ref,
_fake_network_info(self.stubs, 1))
def test_cleanup_resize_not_same_host(self):
host = 'not' + CONF.host
ins_ref = self._create_instance({'host': host})
def fake_os_path_exists(path):
return True
def fake_shutil_rmtree(target):
pass
def fake_undefine_domain(instance):
pass
def fake_unplug_vifs(instance, network_info):
pass
def fake_unfilter_instance(instance, network_info):
pass
self.stubs.Set(os.path, 'exists', fake_os_path_exists)
self.stubs.Set(shutil, 'rmtree', fake_shutil_rmtree)
self.stubs.Set(self.libvirtconnection, '_undefine_domain',
fake_undefine_domain)
self.stubs.Set(self.libvirtconnection, 'unplug_vifs',
fake_unplug_vifs)
self.stubs.Set(self.libvirtconnection.firewall_driver,
'unfilter_instance', fake_unfilter_instance)
self.mox.ReplayAll()
self.libvirtconnection._cleanup_resize(ins_ref,
_fake_network_info(self.stubs, 1))
def test_get_instance_disk_info_exception(self):
instance_name = "fake-instance-name"
class FakeExceptionDomain(FakeVirtDomain):
def __init__(self):
super(FakeExceptionDomain, self).__init__()
def XMLDesc(self, *args):
raise libvirt.libvirtError("Libvirt error")
def fake_lookup_by_name(instance_name):
return FakeExceptionDomain()
self.stubs.Set(self.libvirtconnection, '_lookup_by_name',
fake_lookup_by_name)
self.assertRaises(exception.InstanceNotFound,
self.libvirtconnection.get_instance_disk_info,
instance_name)
def test_get_cpuset_ids(self):
self.flags(vcpu_pin_set="1")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1], cpuset_ids)
self.flags(vcpu_pin_set="1,2")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1, 2], cpuset_ids)
self.flags(vcpu_pin_set=", , 1 , ,, 2, ,")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1, 2], cpuset_ids)
self.flags(vcpu_pin_set="1-1")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1], cpuset_ids)
self.flags(vcpu_pin_set=" 1 - 1, 1 - 2 , 1 -3")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1, 2, 3], cpuset_ids)
self.flags(vcpu_pin_set="1,^2")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1], cpuset_ids)
self.flags(vcpu_pin_set="1-2, ^1")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([2], cpuset_ids)
self.flags(vcpu_pin_set="1-3,5,^2")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1, 3, 5], cpuset_ids)
self.flags(vcpu_pin_set=" 1 - 3 , ^2, 5")
cpuset_ids = self.libvirtconnection._get_cpuset_ids()
self.assertEqual([1, 3, 5], cpuset_ids)
self.flags(vcpu_pin_set=" -1-3,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-3-,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="-3,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-3,5,^2^")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-3,5,^2-")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="--13,^^5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="a-3,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-a,5,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-3,b,^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="1-3,5,^c")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="3 - 1, 5 , ^ 2 ")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set=" 1,1, ^1")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set=" 1,^1,^1,2, ^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
self.flags(vcpu_pin_set="^2")
self.assertRaises(exception.Invalid,
self.libvirtconnection._get_cpuset_ids)
class LibvirtVolumeUsageTestCase(test.TestCase):
"""Test for nova.virt.libvirt.libvirt_driver.LibvirtDriver
.get_all_volume_usage"""
def setUp(self):
super(LibvirtVolumeUsageTestCase, self).setUp()
self.conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.c = context.get_admin_context()
inst = {}
inst['uuid'] = '875a8070-d0b9-4949-8b31-104d125c9a64'
self.ins_ref = db.instance_create(self.c, inst)
self.bdms = [{'volume_id': 1,
'device_name': '/dev/vde'},
{'volume_id': 2,
'device_name': 'vda'}]
def test_get_all_volume_usage(self):
def fake_block_stats(instance_name, disk):
return (169L, 688640L, 0L, 0L, -1L)
self.stubs.Set(self.conn, 'block_stats', fake_block_stats)
vol_usage = self.conn.get_all_volume_usage(self.c,
[dict(instance=self.ins_ref, instance_bdms=self.bdms)])
expected_usage = [{'volume': 1,
'instance': self.ins_ref,
'rd_bytes': 688640L, 'wr_req': 0L,
'flush_operations': -1L, 'rd_req': 169L,
'wr_bytes': 0L},
{'volume': 2,
'instance': self.ins_ref,
'rd_bytes': 688640L, 'wr_req': 0L,
'flush_operations': -1L, 'rd_req': 169L,
'wr_bytes': 0L}]
self.assertEqual(vol_usage, expected_usage)
def test_get_all_volume_usage_device_not_found(self):
def fake_lookup(instance_name):
raise libvirt.libvirtError('invalid path')
self.stubs.Set(self.conn, '_lookup_by_name', fake_lookup)
vol_usage = self.conn.get_all_volume_usage(self.c,
[dict(instance=self.ins_ref, instance_bdms=self.bdms)])
self.assertEqual(vol_usage, [])
class LibvirtNonblockingTestCase(test.TestCase):
"""Test libvirt_nonblocking option."""
def setUp(self):
super(LibvirtNonblockingTestCase, self).setUp()
self.flags(libvirt_nonblocking=True, libvirt_uri="test:///default")
def test_connection_to_primitive(self):
import nova.virt.libvirt.driver as libvirt_driver
connection = libvirt_driver.LibvirtDriver('')
jsonutils.to_primitive(connection._conn, convert_instances=True)
| false | true |
f72c3830b52635d5830fd38ce38096456c2b9555 | 388 | py | Python | bbb/migrations/0007_room_hangout_room.py | cmd-ev/voctoconf | 5d2c1ca4f1da01b66983f5a562eb8eb6babe0452 | [
"MIT"
] | 21 | 2020-08-24T13:27:03.000Z | 2021-10-15T09:17:46.000Z | bbb/migrations/0007_room_hangout_room.py | cmd-ev/voctoconf | 5d2c1ca4f1da01b66983f5a562eb8eb6babe0452 | [
"MIT"
] | null | null | null | bbb/migrations/0007_room_hangout_room.py | cmd-ev/voctoconf | 5d2c1ca4f1da01b66983f5a562eb8eb6babe0452 | [
"MIT"
] | 5 | 2020-08-25T16:34:51.000Z | 2021-02-19T04:48:10.000Z | # Generated by Django 2.2.15 on 2020-08-14 21:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bbb', '0006_auto_20200813_1954'),
]
operations = [
migrations.AddField(
model_name='room',
name='hangout_room',
field=models.BooleanField(default=False),
),
]
| 20.421053 | 53 | 0.600515 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bbb', '0006_auto_20200813_1954'),
]
operations = [
migrations.AddField(
model_name='room',
name='hangout_room',
field=models.BooleanField(default=False),
),
]
| true | true |
f72c386148900925f8177edd4f614faab95b090b | 704 | py | Python | var/spack/repos/builtin/packages/r-biocversion/package.py | player1537-forks/spack | 822b7632222ec5a91dc7b7cda5fc0e08715bd47c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 11 | 2015-10-04T02:17:46.000Z | 2018-02-07T18:23:00.000Z | var/spack/repos/builtin/packages/r-biocversion/package.py | player1537-forks/spack | 822b7632222ec5a91dc7b7cda5fc0e08715bd47c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 22 | 2017-08-01T22:45:10.000Z | 2022-03-10T07:46:31.000Z | var/spack/repos/builtin/packages/r-biocversion/package.py | player1537-forks/spack | 822b7632222ec5a91dc7b7cda5fc0e08715bd47c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 4 | 2016-06-10T17:57:39.000Z | 2018-09-11T04:59:38.000Z | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RBiocversion(RPackage):
"""Set the appropriate version of Bioconductor packages.
This package provides repository information for the appropriate
version of Bioconductor."""
bioc = "BiocVersion"
version('3.14.0', commit='aa56d93d0ea5dcdbf301f120502981740fd91e1e')
version('3.12.0', commit='23b971963c6b73550a7e330dab5a046d58ce0223')
depends_on('r@4.0.0:', type=('build', 'run'))
depends_on('r@4.1.0:', type=('build', 'run'), when='@3.14.0:')
| 32 | 73 | 0.72017 |
from spack import *
class RBiocversion(RPackage):
bioc = "BiocVersion"
version('3.14.0', commit='aa56d93d0ea5dcdbf301f120502981740fd91e1e')
version('3.12.0', commit='23b971963c6b73550a7e330dab5a046d58ce0223')
depends_on('r@4.0.0:', type=('build', 'run'))
depends_on('r@4.1.0:', type=('build', 'run'), when='@3.14.0:')
| true | true |
f72c389a4d7bf918cd68d55d1048f404a1165eda | 274,814 | py | Python | xarray/core/dataset.py | aha66/xarray | 3cbd21aa8fd3a57c0dd324f2a276d83829518331 | [
"CC-BY-4.0",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | xarray/core/dataset.py | aha66/xarray | 3cbd21aa8fd3a57c0dd324f2a276d83829518331 | [
"CC-BY-4.0",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | xarray/core/dataset.py | aha66/xarray | 3cbd21aa8fd3a57c0dd324f2a276d83829518331 | [
"CC-BY-4.0",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | import copy
import datetime
import functools
import inspect
import sys
import warnings
from collections import defaultdict
from distutils.version import LooseVersion
from html import escape
from numbers import Number
from operator import methodcaller
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
DefaultDict,
Dict,
Hashable,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy as np
import pandas as pd
import xarray as xr
from ..coding.cftimeindex import _parse_array_of_cftime_strings
from ..plot.dataset_plot import _Dataset_PlotMethods
from . import (
alignment,
dtypes,
duck_array_ops,
formatting,
formatting_html,
groupby,
ops,
resample,
rolling,
utils,
weighted,
)
from .alignment import _broadcast_helper, _get_broadcast_dims_map_common_coords, align
from .common import (
DataWithCoords,
ImplementsDatasetReduce,
_contains_datetime_like_objects,
)
from .coordinates import (
DatasetCoordinates,
assert_coordinate_consistent,
remap_label_indexers,
)
from .duck_array_ops import datetime_to_numeric
from .indexes import (
Indexes,
default_indexes,
isel_variable_and_index,
propagate_indexes,
remove_unused_levels_categories,
roll_index,
)
from .indexing import is_fancy_indexer
from .merge import (
dataset_merge_method,
dataset_update_method,
merge_coordinates_without_align,
merge_data_and_coords,
)
from .missing import get_clean_interp_index
from .options import OPTIONS, _get_keep_attrs
from .pycompat import is_duck_dask_array, sparse_array_type
from .utils import (
Default,
Frozen,
HybridMappingProxy,
SortedKeysDict,
_default,
decode_numpy_dict_values,
drop_dims_from_indexers,
either_dict_or_kwargs,
hashable,
infix_dims,
is_dict_like,
is_scalar,
maybe_wrap_array,
)
from .variable import (
IndexVariable,
Variable,
as_variable,
assert_unique_multiindex_level_names,
broadcast_variables,
)
if TYPE_CHECKING:
from ..backends import AbstractDataStore, ZarrStore
from .dataarray import DataArray
from .merge import CoercibleMapping
T_DSorDA = TypeVar("T_DSorDA", DataArray, "Dataset")
try:
from dask.delayed import Delayed
except ImportError:
Delayed = None
# list of attributes of pd.DatetimeIndex that are ndarrays of time info
_DATETIMEINDEX_COMPONENTS = [
"year",
"month",
"day",
"hour",
"minute",
"second",
"microsecond",
"nanosecond",
"date",
"time",
"dayofyear",
"weekofyear",
"dayofweek",
"quarter",
]
def _get_virtual_variable(
variables, key: Hashable, level_vars: Mapping = None, dim_sizes: Mapping = None
) -> Tuple[Hashable, Hashable, Variable]:
"""Get a virtual variable (e.g., 'time.year' or a MultiIndex level)
from a dict of xarray.Variable objects (if possible)
"""
if level_vars is None:
level_vars = {}
if dim_sizes is None:
dim_sizes = {}
if key in dim_sizes:
data = pd.Index(range(dim_sizes[key]), name=key)
variable = IndexVariable((key,), data)
return key, key, variable
if not isinstance(key, str):
raise KeyError(key)
split_key = key.split(".", 1)
var_name: Optional[str]
if len(split_key) == 2:
ref_name, var_name = split_key
elif len(split_key) == 1:
ref_name, var_name = key, None
else:
raise KeyError(key)
if ref_name in level_vars:
dim_var = variables[level_vars[ref_name]]
ref_var = dim_var.to_index_variable().get_level_variable(ref_name)
else:
ref_var = variables[ref_name]
if var_name is None:
virtual_var = ref_var
var_name = key
else:
if _contains_datetime_like_objects(ref_var):
ref_var = xr.DataArray(ref_var)
data = getattr(ref_var.dt, var_name).data
else:
data = getattr(ref_var, var_name).data
virtual_var = Variable(ref_var.dims, data)
return ref_name, var_name, virtual_var
def calculate_dimensions(variables: Mapping[Hashable, Variable]) -> Dict[Hashable, int]:
"""Calculate the dimensions corresponding to a set of variables.
Returns dictionary mapping from dimension names to sizes. Raises ValueError
if any of the dimension sizes conflict.
"""
dims: Dict[Hashable, int] = {}
last_used = {}
scalar_vars = {k for k, v in variables.items() if not v.dims}
for k, var in variables.items():
for dim, size in zip(var.dims, var.shape):
if dim in scalar_vars:
raise ValueError(
"dimension %r already exists as a scalar variable" % dim
)
if dim not in dims:
dims[dim] = size
last_used[dim] = k
elif dims[dim] != size:
raise ValueError(
"conflicting sizes for dimension %r: "
"length %s on %r and length %s on %r"
% (dim, size, k, dims[dim], last_used[dim])
)
return dims
def merge_indexes(
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]],
variables: Mapping[Hashable, Variable],
coord_names: Set[Hashable],
append: bool = False,
) -> Tuple[Dict[Hashable, Variable], Set[Hashable]]:
"""Merge variables into multi-indexes.
Not public API. Used in Dataset and DataArray set_index
methods.
"""
vars_to_replace: Dict[Hashable, Variable] = {}
vars_to_remove: List[Hashable] = []
dims_to_replace: Dict[Hashable, Hashable] = {}
error_msg = "{} is not the name of an existing variable."
for dim, var_names in indexes.items():
if isinstance(var_names, str) or not isinstance(var_names, Sequence):
var_names = [var_names]
names: List[Hashable] = []
codes: List[List[int]] = []
levels: List[List[int]] = []
current_index_variable = variables.get(dim)
for n in var_names:
try:
var = variables[n]
except KeyError:
raise ValueError(error_msg.format(n))
if (
current_index_variable is not None
and var.dims != current_index_variable.dims
):
raise ValueError(
"dimension mismatch between %r %s and %r %s"
% (dim, current_index_variable.dims, n, var.dims)
)
if current_index_variable is not None and append:
current_index = current_index_variable.to_index()
if isinstance(current_index, pd.MultiIndex):
names.extend(current_index.names)
codes.extend(current_index.codes)
levels.extend(current_index.levels)
else:
names.append("%s_level_0" % dim)
cat = pd.Categorical(current_index.values, ordered=True)
codes.append(cat.codes)
levels.append(cat.categories)
if not len(names) and len(var_names) == 1:
idx = pd.Index(variables[var_names[0]].values)
else: # MultiIndex
for n in var_names:
try:
var = variables[n]
except KeyError:
raise ValueError(error_msg.format(n))
names.append(n)
cat = pd.Categorical(var.values, ordered=True)
codes.append(cat.codes)
levels.append(cat.categories)
idx = pd.MultiIndex(levels, codes, names=names)
for n in names:
dims_to_replace[n] = dim
vars_to_replace[dim] = IndexVariable(dim, idx)
vars_to_remove.extend(var_names)
new_variables = {k: v for k, v in variables.items() if k not in vars_to_remove}
new_variables.update(vars_to_replace)
# update dimensions if necessary, GH: 3512
for k, v in new_variables.items():
if any(d in dims_to_replace for d in v.dims):
new_dims = [dims_to_replace.get(d, d) for d in v.dims]
new_variables[k] = v._replace(dims=new_dims)
new_coord_names = coord_names | set(vars_to_replace)
new_coord_names -= set(vars_to_remove)
return new_variables, new_coord_names
def split_indexes(
dims_or_levels: Union[Hashable, Sequence[Hashable]],
variables: Mapping[Hashable, Variable],
coord_names: Set[Hashable],
level_coords: Mapping[Hashable, Hashable],
drop: bool = False,
) -> Tuple[Dict[Hashable, Variable], Set[Hashable]]:
"""Extract (multi-)indexes (levels) as variables.
Not public API. Used in Dataset and DataArray reset_index
methods.
"""
if isinstance(dims_or_levels, str) or not isinstance(dims_or_levels, Sequence):
dims_or_levels = [dims_or_levels]
dim_levels: DefaultDict[Any, List[Hashable]] = defaultdict(list)
dims = []
for k in dims_or_levels:
if k in level_coords:
dim_levels[level_coords[k]].append(k)
else:
dims.append(k)
vars_to_replace = {}
vars_to_create: Dict[Hashable, Variable] = {}
vars_to_remove = []
for d in dims:
index = variables[d].to_index()
if isinstance(index, pd.MultiIndex):
dim_levels[d] = index.names
else:
vars_to_remove.append(d)
if not drop:
vars_to_create[str(d) + "_"] = Variable(d, index, variables[d].attrs)
for d, levs in dim_levels.items():
index = variables[d].to_index()
if len(levs) == index.nlevels:
vars_to_remove.append(d)
else:
vars_to_replace[d] = IndexVariable(d, index.droplevel(levs))
if not drop:
for lev in levs:
idx = index.get_level_values(lev)
vars_to_create[idx.name] = Variable(d, idx, variables[d].attrs)
new_variables = dict(variables)
for v in set(vars_to_remove):
del new_variables[v]
new_variables.update(vars_to_replace)
new_variables.update(vars_to_create)
new_coord_names = (coord_names | set(vars_to_create)) - set(vars_to_remove)
return new_variables, new_coord_names
def _assert_empty(args: tuple, msg: str = "%s") -> None:
if args:
raise ValueError(msg % args)
def _check_chunks_compatibility(var, chunks, preferred_chunks):
for dim in var.dims:
if dim not in chunks or (dim not in preferred_chunks):
continue
preferred_chunks_dim = preferred_chunks.get(dim)
chunks_dim = chunks.get(dim)
if isinstance(chunks_dim, int):
chunks_dim = (chunks_dim,)
else:
chunks_dim = chunks_dim[:-1]
if any(s % preferred_chunks_dim for s in chunks_dim):
warnings.warn(
f"Specified Dask chunks {chunks[dim]} would separate "
f"on disks chunk shape {preferred_chunks[dim]} for dimension {dim}. "
"This could degrade performance. "
"Consider rechunking after loading instead.",
stacklevel=2,
)
def _get_chunk(var, chunks):
# chunks need to be explicity computed to take correctly into accout
# backend preferred chunking
import dask.array as da
if isinstance(var, IndexVariable):
return {}
if isinstance(chunks, int) or (chunks == "auto"):
chunks = dict.fromkeys(var.dims, chunks)
preferred_chunks = var.encoding.get("preferred_chunks", {})
preferred_chunks_list = [
preferred_chunks.get(dim, shape) for dim, shape in zip(var.dims, var.shape)
]
chunks_list = [
chunks.get(dim, None) or preferred_chunks.get(dim, None) for dim in var.dims
]
output_chunks_list = da.core.normalize_chunks(
chunks_list,
shape=var.shape,
dtype=var.dtype,
previous_chunks=preferred_chunks_list,
)
output_chunks = dict(zip(var.dims, output_chunks_list))
_check_chunks_compatibility(var, output_chunks, preferred_chunks)
return output_chunks
def _maybe_chunk(
name,
var,
chunks,
token=None,
lock=None,
name_prefix="xarray-",
overwrite_encoded_chunks=False,
):
from dask.base import tokenize
if chunks is not None:
chunks = {dim: chunks[dim] for dim in var.dims if dim in chunks}
if var.ndim:
# when rechunking by different amounts, make sure dask names change
# by provinding chunks as an input to tokenize.
# subtle bugs result otherwise. see GH3350
token2 = tokenize(name, token if token else var._data, chunks)
name2 = f"{name_prefix}{name}-{token2}"
var = var.chunk(chunks, name=name2, lock=lock)
if overwrite_encoded_chunks and var.chunks is not None:
var.encoding["chunks"] = tuple(x[0] for x in var.chunks)
return var
else:
return var
def as_dataset(obj: Any) -> "Dataset":
"""Cast the given object to a Dataset.
Handles Datasets, DataArrays and dictionaries of variables. A new Dataset
object is only created if the provided object is not already one.
"""
if hasattr(obj, "to_dataset"):
obj = obj.to_dataset()
if not isinstance(obj, Dataset):
obj = Dataset(obj)
return obj
def _get_func_args(func, param_names):
"""Use `inspect.signature` to try accessing `func` args. Otherwise, ensure
they are provided by user.
"""
try:
func_args = inspect.signature(func).parameters
except ValueError:
func_args = {}
if not param_names:
raise ValueError(
"Unable to inspect `func` signature, and `param_names` was not provided."
)
if param_names:
params = param_names
else:
params = list(func_args)[1:]
if any(
[(p.kind in [p.VAR_POSITIONAL, p.VAR_KEYWORD]) for p in func_args.values()]
):
raise ValueError(
"`param_names` must be provided because `func` takes variable length arguments."
)
return params, func_args
def _initialize_curvefit_params(params, p0, bounds, func_args):
"""Set initial guess and bounds for curvefit.
Priority: 1) passed args 2) func signature 3) scipy defaults
"""
def _initialize_feasible(lb, ub):
# Mimics functionality of scipy.optimize.minpack._initialize_feasible
lb_finite = np.isfinite(lb)
ub_finite = np.isfinite(ub)
p0 = np.nansum(
[
0.5 * (lb + ub) * int(lb_finite & ub_finite),
(lb + 1) * int(lb_finite & ~ub_finite),
(ub - 1) * int(~lb_finite & ub_finite),
]
)
return p0
param_defaults = {p: 1 for p in params}
bounds_defaults = {p: (-np.inf, np.inf) for p in params}
for p in params:
if p in func_args and func_args[p].default is not func_args[p].empty:
param_defaults[p] = func_args[p].default
if p in bounds:
bounds_defaults[p] = tuple(bounds[p])
if param_defaults[p] < bounds[p][0] or param_defaults[p] > bounds[p][1]:
param_defaults[p] = _initialize_feasible(bounds[p][0], bounds[p][1])
if p in p0:
param_defaults[p] = p0[p]
return param_defaults, bounds_defaults
class DataVariables(Mapping[Hashable, "DataArray"]):
__slots__ = ("_dataset",)
def __init__(self, dataset: "Dataset"):
self._dataset = dataset
def __iter__(self) -> Iterator[Hashable]:
return (
key
for key in self._dataset._variables
if key not in self._dataset._coord_names
)
def __len__(self) -> int:
return len(self._dataset._variables) - len(self._dataset._coord_names)
def __contains__(self, key: Hashable) -> bool:
return key in self._dataset._variables and key not in self._dataset._coord_names
def __getitem__(self, key: Hashable) -> "DataArray":
if key not in self._dataset._coord_names:
return cast("DataArray", self._dataset[key])
raise KeyError(key)
def __repr__(self) -> str:
return formatting.data_vars_repr(self)
@property
def variables(self) -> Mapping[Hashable, Variable]:
all_variables = self._dataset.variables
return Frozen({k: all_variables[k] for k in self})
def _ipython_key_completions_(self):
"""Provide method for the key-autocompletions in IPython. """
return [
key
for key in self._dataset._ipython_key_completions_()
if key not in self._dataset._coord_names
]
class _LocIndexer:
__slots__ = ("dataset",)
def __init__(self, dataset: "Dataset"):
self.dataset = dataset
def __getitem__(self, key: Mapping[Hashable, Any]) -> "Dataset":
if not utils.is_dict_like(key):
raise TypeError("can only lookup dictionaries from Dataset.loc")
return self.dataset.sel(key)
class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords):
"""A multi-dimensional, in memory, array database.
A dataset resembles an in-memory representation of a NetCDF file,
and consists of variables, coordinates and attributes which
together form a self describing dataset.
Dataset implements the mapping interface with keys given by variable
names and values given by DataArray objects for each variable name.
One dimensional variables with name equal to their dimension are
index coordinates used for label based indexing.
To load data from a file or file-like object, use the `open_dataset`
function.
Parameters
----------
data_vars : dict-like, optional
A mapping from variable names to :py:class:`~xarray.DataArray`
objects, :py:class:`~xarray.Variable` objects or to tuples of
the form ``(dims, data[, attrs])`` which can be used as
arguments to create a new ``Variable``. Each dimension must
have the same length in all variables in which it appears.
The following notations are accepted:
- mapping {var name: DataArray}
- mapping {var name: Variable}
- mapping {var name: (dimension name, array-like)}
- mapping {var name: (tuple of dimension names, array-like)}
- mapping {dimension name: array-like}
(it will be automatically moved to coords, see below)
Each dimension must have the same length in all variables in
which it appears.
coords : dict-like, optional
Another mapping in similar form as the `data_vars` argument,
except the each item is saved on the dataset as a "coordinate".
These variables have an associated meaning: they describe
constant/fixed/independent quantities, unlike the
varying/measured/dependent quantities that belong in
`variables`. Coordinates values may be given by 1-dimensional
arrays or scalars, in which case `dims` do not need to be
supplied: 1D arrays will be assumed to give index values along
the dimension with the same name.
The following notations are accepted:
- mapping {coord name: DataArray}
- mapping {coord name: Variable}
- mapping {coord name: (dimension name, array-like)}
- mapping {coord name: (tuple of dimension names, array-like)}
- mapping {dimension name: array-like}
(the dimension name is implicitly set to be the same as the
coord name)
The last notation implies that the coord name is the same as
the dimension name.
attrs : dict-like, optional
Global attributes to save on this dataset.
Examples
--------
Create data:
>>> np.random.seed(0)
>>> temperature = 15 + 8 * np.random.randn(2, 2, 3)
>>> precipitation = 10 * np.random.rand(2, 2, 3)
>>> lon = [[-99.83, -99.32], [-99.79, -99.23]]
>>> lat = [[42.25, 42.21], [42.63, 42.59]]
>>> time = pd.date_range("2014-09-06", periods=3)
>>> reference_time = pd.Timestamp("2014-09-05")
Initialize a dataset with multiple dimensions:
>>> ds = xr.Dataset(
... data_vars=dict(
... temperature=(["x", "y", "time"], temperature),
... precipitation=(["x", "y", "time"], precipitation),
... ),
... coords=dict(
... lon=(["x", "y"], lon),
... lat=(["x", "y"], lat),
... time=time,
... reference_time=reference_time,
... ),
... attrs=dict(description="Weather related data."),
... )
>>> ds
<xarray.Dataset>
Dimensions: (time: 3, x: 2, y: 2)
Coordinates:
lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
lat (x, y) float64 42.25 42.21 42.63 42.59
* time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
reference_time datetime64[ns] 2014-09-05
Dimensions without coordinates: x, y
Data variables:
temperature (x, y, time) float64 29.11 18.2 22.83 ... 18.28 16.15 26.63
precipitation (x, y, time) float64 5.68 9.256 0.7104 ... 7.992 4.615 7.805
Attributes:
description: Weather related data.
Find out where the coldest temperature was and what values the
other variables had:
>>> ds.isel(ds.temperature.argmin(...))
<xarray.Dataset>
Dimensions: ()
Coordinates:
lon float64 -99.32
lat float64 42.21
time datetime64[ns] 2014-09-08
reference_time datetime64[ns] 2014-09-05
Data variables:
temperature float64 7.182
precipitation float64 8.326
Attributes:
description: Weather related data.
"""
_attrs: Optional[Dict[Hashable, Any]]
_cache: Dict[str, Any]
_coord_names: Set[Hashable]
_dims: Dict[Hashable, int]
_encoding: Optional[Dict[Hashable, Any]]
_close: Optional[Callable[[], None]]
_indexes: Optional[Dict[Hashable, pd.Index]]
_variables: Dict[Hashable, Variable]
__slots__ = (
"_attrs",
"_cache",
"_coord_names",
"_dims",
"_encoding",
"_close",
"_indexes",
"_variables",
"__weakref__",
)
_groupby_cls = groupby.DatasetGroupBy
_rolling_cls = rolling.DatasetRolling
_coarsen_cls = rolling.DatasetCoarsen
_resample_cls = resample.DatasetResample
_weighted_cls = weighted.DatasetWeighted
def __init__(
self,
# could make a VariableArgs to use more generally, and refine these
# categories
data_vars: Mapping[Hashable, Any] = None,
coords: Mapping[Hashable, Any] = None,
attrs: Mapping[Hashable, Any] = None,
):
# TODO(shoyer): expose indexes as a public argument in __init__
if data_vars is None:
data_vars = {}
if coords is None:
coords = {}
both_data_and_coords = set(data_vars) & set(coords)
if both_data_and_coords:
raise ValueError(
"variables %r are found in both data_vars and coords"
% both_data_and_coords
)
if isinstance(coords, Dataset):
coords = coords.variables
variables, coord_names, dims, indexes, _ = merge_data_and_coords(
data_vars, coords, compat="broadcast_equals"
)
self._attrs = dict(attrs) if attrs is not None else None
self._close = None
self._encoding = None
self._variables = variables
self._coord_names = coord_names
self._dims = dims
self._indexes = indexes
@classmethod
def load_store(cls, store, decoder=None) -> "Dataset":
"""Create a new dataset from the contents of a backends.*DataStore
object
"""
variables, attributes = store.load()
if decoder:
variables, attributes = decoder(variables, attributes)
obj = cls(variables, attrs=attributes)
obj.set_close(store.close)
return obj
@property
def variables(self) -> Mapping[Hashable, Variable]:
"""Low level interface to Dataset contents as dict of Variable objects.
This ordered dictionary is frozen to prevent mutation that could
violate Dataset invariants. It contains all variable objects
constituting the Dataset, including both data variables and
coordinates.
"""
return Frozen(self._variables)
@property
def attrs(self) -> Dict[Hashable, Any]:
"""Dictionary of global attributes on this dataset"""
if self._attrs is None:
self._attrs = {}
return self._attrs
@attrs.setter
def attrs(self, value: Mapping[Hashable, Any]) -> None:
self._attrs = dict(value)
@property
def encoding(self) -> Dict:
"""Dictionary of global encoding attributes on this dataset"""
if self._encoding is None:
self._encoding = {}
return self._encoding
@encoding.setter
def encoding(self, value: Mapping) -> None:
self._encoding = dict(value)
@property
def dims(self) -> Mapping[Hashable, int]:
"""Mapping from dimension names to lengths.
Cannot be modified directly, but is updated when adding new variables.
Note that type of this object differs from `DataArray.dims`.
See `Dataset.sizes` and `DataArray.sizes` for consistently named
properties.
"""
return Frozen(SortedKeysDict(self._dims))
@property
def sizes(self) -> Mapping[Hashable, int]:
"""Mapping from dimension names to lengths.
Cannot be modified directly, but is updated when adding new variables.
This is an alias for `Dataset.dims` provided for the benefit of
consistency with `DataArray.sizes`.
See Also
--------
DataArray.sizes
"""
return self.dims
def load(self, **kwargs) -> "Dataset":
"""Manually trigger loading and/or computation of this dataset's data
from disk or a remote source into memory and return this dataset.
Unlike compute, the original dataset is modified and returned.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data or
load data automatically. However, this method can be necessary when
working with many file objects on disk.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.compute``.
See Also
--------
dask.compute
"""
# access .data to coerce everything to numpy or dask arrays
lazy_data = {
k: v._data for k, v in self.variables.items() if is_duck_dask_array(v._data)
}
if lazy_data:
import dask.array as da
# evaluate all the dask arrays simultaneously
evaluated_data = da.compute(*lazy_data.values(), **kwargs)
for k, data in zip(lazy_data, evaluated_data):
self.variables[k].data = data
# load everything else sequentially
for k, v in self.variables.items():
if k not in lazy_data:
v.load()
return self
def __dask_tokenize__(self):
from dask.base import normalize_token
return normalize_token(
(type(self), self._variables, self._coord_names, self._attrs)
)
def __dask_graph__(self):
graphs = {k: v.__dask_graph__() for k, v in self.variables.items()}
graphs = {k: v for k, v in graphs.items() if v is not None}
if not graphs:
return None
else:
try:
from dask.highlevelgraph import HighLevelGraph
return HighLevelGraph.merge(*graphs.values())
except ImportError:
from dask import sharedict
return sharedict.merge(*graphs.values())
def __dask_keys__(self):
import dask
return [
v.__dask_keys__()
for v in self.variables.values()
if dask.is_dask_collection(v)
]
def __dask_layers__(self):
import dask
return sum(
[
v.__dask_layers__()
for v in self.variables.values()
if dask.is_dask_collection(v)
],
(),
)
@property
def __dask_optimize__(self):
import dask.array as da
return da.Array.__dask_optimize__
@property
def __dask_scheduler__(self):
import dask.array as da
return da.Array.__dask_scheduler__
def __dask_postcompute__(self):
return self._dask_postcompute, ()
def __dask_postpersist__(self):
return self._dask_postpersist, ()
def _dask_postcompute(self, results: "Iterable[Variable]") -> "Dataset":
import dask
variables = {}
results_iter = iter(results)
for k, v in self._variables.items():
if dask.is_dask_collection(v):
rebuild, args = v.__dask_postcompute__()
v = rebuild(next(results_iter), *args)
variables[k] = v
return Dataset._construct_direct(
variables,
self._coord_names,
self._dims,
self._attrs,
self._indexes,
self._encoding,
self._close,
)
def _dask_postpersist(
self, dsk: Mapping, *, rename: Mapping[str, str] = None
) -> "Dataset":
from dask import is_dask_collection
from dask.highlevelgraph import HighLevelGraph
from dask.optimization import cull
variables = {}
for k, v in self._variables.items():
if not is_dask_collection(v):
variables[k] = v
continue
if isinstance(dsk, HighLevelGraph):
# dask >= 2021.3
# __dask_postpersist__() was called by dask.highlevelgraph.
# Don't use dsk.cull(), as we need to prevent partial layers:
# https://github.com/dask/dask/issues/7137
layers = v.__dask_layers__()
if rename:
layers = [rename.get(k, k) for k in layers]
dsk2 = dsk.cull_layers(layers)
elif rename: # pragma: nocover
# At the moment of writing, this is only for forward compatibility.
# replace_name_in_key requires dask >= 2021.3.
from dask.base import flatten, replace_name_in_key
keys = [
replace_name_in_key(k, rename) for k in flatten(v.__dask_keys__())
]
dsk2, _ = cull(dsk, keys)
else:
# __dask_postpersist__() was called by dask.optimize or dask.persist
dsk2, _ = cull(dsk, v.__dask_keys__())
rebuild, args = v.__dask_postpersist__()
# rename was added in dask 2021.3
kwargs = {"rename": rename} if rename else {}
variables[k] = rebuild(dsk2, *args, **kwargs)
return Dataset._construct_direct(
variables,
self._coord_names,
self._dims,
self._attrs,
self._indexes,
self._encoding,
self._close,
)
def compute(self, **kwargs) -> "Dataset":
"""Manually trigger loading and/or computation of this dataset's data
from disk or a remote source into memory and return a new dataset.
Unlike load, the original dataset is left unaltered.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data or
load data automatically. However, this method can be necessary when
working with many file objects on disk.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.compute``.
See Also
--------
dask.compute
"""
new = self.copy(deep=False)
return new.load(**kwargs)
def _persist_inplace(self, **kwargs) -> "Dataset":
"""Persist all Dask arrays in memory"""
# access .data to coerce everything to numpy or dask arrays
lazy_data = {
k: v._data for k, v in self.variables.items() if is_duck_dask_array(v._data)
}
if lazy_data:
import dask
# evaluate all the dask arrays simultaneously
evaluated_data = dask.persist(*lazy_data.values(), **kwargs)
for k, data in zip(lazy_data, evaluated_data):
self.variables[k].data = data
return self
def persist(self, **kwargs) -> "Dataset":
"""Trigger computation, keeping data as dask arrays
This operation can be used to trigger computation on underlying dask
arrays, similar to ``.compute()`` or ``.load()``. However this
operation keeps the data as dask arrays. This is particularly useful
when using the dask.distributed scheduler and you want to load a large
amount of data into distributed memory.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.persist``.
See Also
--------
dask.persist
"""
new = self.copy(deep=False)
return new._persist_inplace(**kwargs)
@classmethod
def _construct_direct(
cls,
variables,
coord_names,
dims=None,
attrs=None,
indexes=None,
encoding=None,
close=None,
):
"""Shortcut around __init__ for internal use when we want to skip
costly validation
"""
if dims is None:
dims = calculate_dimensions(variables)
obj = object.__new__(cls)
obj._variables = variables
obj._coord_names = coord_names
obj._dims = dims
obj._indexes = indexes
obj._attrs = attrs
obj._close = close
obj._encoding = encoding
return obj
def _replace(
self,
variables: Dict[Hashable, Variable] = None,
coord_names: Set[Hashable] = None,
dims: Dict[Any, int] = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
indexes: Union[Dict[Any, pd.Index], None, Default] = _default,
encoding: Union[dict, None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
"""Fastpath constructor for internal use.
Returns an object with optionally with replaced attributes.
Explicitly passed arguments are *not* copied when placed on the new
dataset. It is up to the caller to ensure that they have the right type
and are not used elsewhere.
"""
if inplace:
if variables is not None:
self._variables = variables
if coord_names is not None:
self._coord_names = coord_names
if dims is not None:
self._dims = dims
if attrs is not _default:
self._attrs = attrs
if indexes is not _default:
self._indexes = indexes
if encoding is not _default:
self._encoding = encoding
obj = self
else:
if variables is None:
variables = self._variables.copy()
if coord_names is None:
coord_names = self._coord_names.copy()
if dims is None:
dims = self._dims.copy()
if attrs is _default:
attrs = copy.copy(self._attrs)
if indexes is _default:
indexes = copy.copy(self._indexes)
if encoding is _default:
encoding = copy.copy(self._encoding)
obj = self._construct_direct(
variables, coord_names, dims, attrs, indexes, encoding
)
return obj
def _replace_with_new_dims(
self,
variables: Dict[Hashable, Variable],
coord_names: set = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
indexes: Union[Dict[Hashable, pd.Index], None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
"""Replace variables with recalculated dimensions."""
dims = calculate_dimensions(variables)
return self._replace(
variables, coord_names, dims, attrs, indexes, inplace=inplace
)
def _replace_vars_and_dims(
self,
variables: Dict[Hashable, Variable],
coord_names: set = None,
dims: Dict[Hashable, int] = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
"""Deprecated version of _replace_with_new_dims().
Unlike _replace_with_new_dims(), this method always recalculates
indexes from variables.
"""
if dims is None:
dims = calculate_dimensions(variables)
return self._replace(
variables, coord_names, dims, attrs, indexes=None, inplace=inplace
)
def _overwrite_indexes(self, indexes: Mapping[Any, pd.Index]) -> "Dataset":
if not indexes:
return self
variables = self._variables.copy()
new_indexes = dict(self.indexes)
for name, idx in indexes.items():
variables[name] = IndexVariable(name, idx)
new_indexes[name] = idx
obj = self._replace(variables, indexes=new_indexes)
# switch from dimension to level names, if necessary
dim_names: Dict[Hashable, str] = {}
for dim, idx in indexes.items():
if not isinstance(idx, pd.MultiIndex) and idx.name != dim:
dim_names[dim] = idx.name
if dim_names:
obj = obj.rename(dim_names)
return obj
def copy(self, deep: bool = False, data: Mapping = None) -> "Dataset":
"""Returns a copy of this dataset.
If `deep=True`, a deep copy is made of each of the component variables.
Otherwise, a shallow copy of each of the component variable is made, so
that the underlying memory region of the new dataset is the same as in
the original dataset.
Use `data` to create a new object with the same structure as
original but entirely new data.
Parameters
----------
deep : bool, optional
Whether each component variable is loaded into memory and copied onto
the new object. Default is False.
data : dict-like, optional
Data to use in the new object. Each item in `data` must have same
shape as corresponding data variable in original. When `data` is
used, `deep` is ignored for the data variables and only used for
coords.
Returns
-------
object : Dataset
New object with dimensions, attributes, coordinates, name, encoding,
and optionally data copied from original.
Examples
--------
Shallow copy versus deep copy
>>> da = xr.DataArray(np.random.randn(2, 3))
>>> ds = xr.Dataset(
... {"foo": da, "bar": ("x", [-1, 2])},
... coords={"x": ["one", "two"]},
... )
>>> ds.copy()
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Coordinates:
* x (x) <U3 'one' 'two'
Dimensions without coordinates: dim_0, dim_1
Data variables:
foo (dim_0, dim_1) float64 1.764 0.4002 0.9787 2.241 1.868 -0.9773
bar (x) int64 -1 2
>>> ds_0 = ds.copy(deep=False)
>>> ds_0["foo"][0, 0] = 7
>>> ds_0
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Coordinates:
* x (x) <U3 'one' 'two'
Dimensions without coordinates: dim_0, dim_1
Data variables:
foo (dim_0, dim_1) float64 7.0 0.4002 0.9787 2.241 1.868 -0.9773
bar (x) int64 -1 2
>>> ds
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Coordinates:
* x (x) <U3 'one' 'two'
Dimensions without coordinates: dim_0, dim_1
Data variables:
foo (dim_0, dim_1) float64 7.0 0.4002 0.9787 2.241 1.868 -0.9773
bar (x) int64 -1 2
Changing the data using the ``data`` argument maintains the
structure of the original object, but with the new data. Original
object is unaffected.
>>> ds.copy(data={"foo": np.arange(6).reshape(2, 3), "bar": ["a", "b"]})
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Coordinates:
* x (x) <U3 'one' 'two'
Dimensions without coordinates: dim_0, dim_1
Data variables:
foo (dim_0, dim_1) int64 0 1 2 3 4 5
bar (x) <U1 'a' 'b'
>>> ds
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Coordinates:
* x (x) <U3 'one' 'two'
Dimensions without coordinates: dim_0, dim_1
Data variables:
foo (dim_0, dim_1) float64 7.0 0.4002 0.9787 2.241 1.868 -0.9773
bar (x) int64 -1 2
See Also
--------
pandas.DataFrame.copy
"""
if data is None:
variables = {k: v.copy(deep=deep) for k, v in self._variables.items()}
elif not utils.is_dict_like(data):
raise ValueError("Data must be dict-like")
else:
var_keys = set(self.data_vars.keys())
data_keys = set(data.keys())
keys_not_in_vars = data_keys - var_keys
if keys_not_in_vars:
raise ValueError(
"Data must only contain variables in original "
"dataset. Extra variables: {}".format(keys_not_in_vars)
)
keys_missing_from_data = var_keys - data_keys
if keys_missing_from_data:
raise ValueError(
"Data must contain all variables in original "
"dataset. Data is missing {}".format(keys_missing_from_data)
)
variables = {
k: v.copy(deep=deep, data=data.get(k))
for k, v in self._variables.items()
}
attrs = copy.deepcopy(self._attrs) if deep else copy.copy(self._attrs)
return self._replace(variables, attrs=attrs)
@property
def _level_coords(self) -> Dict[str, Hashable]:
"""Return a mapping of all MultiIndex levels and their corresponding
coordinate name.
"""
level_coords: Dict[str, Hashable] = {}
for name, index in self.indexes.items():
if isinstance(index, pd.MultiIndex):
level_names = index.names
(dim,) = self.variables[name].dims
level_coords.update({lname: dim for lname in level_names})
return level_coords
def _copy_listed(self, names: Iterable[Hashable]) -> "Dataset":
"""Create a new Dataset with the listed variables from this dataset and
the all relevant coordinates. Skips all validation.
"""
variables: Dict[Hashable, Variable] = {}
coord_names = set()
indexes: Dict[Hashable, pd.Index] = {}
for name in names:
try:
variables[name] = self._variables[name]
except KeyError:
ref_name, var_name, var = _get_virtual_variable(
self._variables, name, self._level_coords, self.dims
)
variables[var_name] = var
if ref_name in self._coord_names or ref_name in self.dims:
coord_names.add(var_name)
if (var_name,) == var.dims:
indexes[var_name] = var.to_index()
needed_dims: Set[Hashable] = set()
for v in variables.values():
needed_dims.update(v.dims)
dims = {k: self.dims[k] for k in needed_dims}
# preserves ordering of coordinates
for k in self._variables:
if k not in self._coord_names:
continue
if set(self.variables[k].dims) <= needed_dims:
variables[k] = self._variables[k]
coord_names.add(k)
if k in self.indexes:
indexes[k] = self.indexes[k]
return self._replace(variables, coord_names, dims, indexes=indexes)
def _construct_dataarray(self, name: Hashable) -> "DataArray":
"""Construct a DataArray by indexing this dataset"""
from .dataarray import DataArray
try:
variable = self._variables[name]
except KeyError:
_, name, variable = _get_virtual_variable(
self._variables, name, self._level_coords, self.dims
)
needed_dims = set(variable.dims)
coords: Dict[Hashable, Variable] = {}
# preserve ordering
for k in self._variables:
if k in self._coord_names and set(self.variables[k].dims) <= needed_dims:
coords[k] = self.variables[k]
if self._indexes is None:
indexes = None
else:
indexes = {k: v for k, v in self._indexes.items() if k in coords}
return DataArray(variable, coords, name=name, indexes=indexes, fastpath=True)
def __copy__(self) -> "Dataset":
return self.copy(deep=False)
def __deepcopy__(self, memo=None) -> "Dataset":
# memo does nothing but is required for compatibility with
# copy.deepcopy
return self.copy(deep=True)
@property
def _attr_sources(self) -> Iterable[Mapping[Hashable, Any]]:
"""Places to look-up items for attribute-style access"""
yield from self._item_sources
yield self.attrs
@property
def _item_sources(self) -> Iterable[Mapping[Hashable, Any]]:
"""Places to look-up items for key-completion"""
yield self.data_vars
yield HybridMappingProxy(keys=self._coord_names, mapping=self.coords)
# virtual coordinates
yield HybridMappingProxy(keys=self.dims, mapping=self)
# uses empty dict -- everything here can already be found in self.coords.
yield HybridMappingProxy(keys=self._level_coords, mapping={})
def __contains__(self, key: object) -> bool:
"""The 'in' operator will return true or false depending on whether
'key' is an array in the dataset or not.
"""
return key in self._variables
def __len__(self) -> int:
return len(self.data_vars)
def __bool__(self) -> bool:
return bool(self.data_vars)
def __iter__(self) -> Iterator[Hashable]:
return iter(self.data_vars)
def __array__(self, dtype=None):
raise TypeError(
"cannot directly convert an xarray.Dataset into a "
"numpy array. Instead, create an xarray.DataArray "
"first, either with indexing on the Dataset or by "
"invoking the `to_array()` method."
)
@property
def nbytes(self) -> int:
return sum(v.nbytes for v in self.variables.values())
@property
def loc(self) -> _LocIndexer:
"""Attribute for location based indexing. Only supports __getitem__,
and only when the key is a dict of the form {dim: labels}.
"""
return _LocIndexer(self)
# FIXME https://github.com/python/mypy/issues/7328
@overload
def __getitem__(self, key: Mapping) -> "Dataset": # type: ignore[misc]
...
@overload
def __getitem__(self, key: Hashable) -> "DataArray": # type: ignore[misc]
...
@overload
def __getitem__(self, key: Any) -> "Dataset":
...
def __getitem__(self, key):
"""Access variables or coordinates this dataset as a
:py:class:`~xarray.DataArray`.
Indexing with a list of names will return a new ``Dataset`` object.
"""
if utils.is_dict_like(key):
return self.isel(**cast(Mapping, key))
if hashable(key):
return self._construct_dataarray(key)
else:
return self._copy_listed(np.asarray(key))
def __setitem__(self, key: Hashable, value) -> None:
"""Add an array to this dataset.
If value is a `DataArray`, call its `select_vars()` method, rename it
to `key` and merge the contents of the resulting dataset into this
dataset.
If value is an `Variable` object (or tuple of form
``(dims, data[, attrs])``), add it to this dataset as a new
variable.
"""
if utils.is_dict_like(key):
raise NotImplementedError(
"cannot yet use a dictionary as a key to set Dataset values"
)
self.update({key: value})
def __delitem__(self, key: Hashable) -> None:
"""Remove a variable from this dataset."""
del self._variables[key]
self._coord_names.discard(key)
if key in self.indexes:
assert self._indexes is not None
del self._indexes[key]
self._dims = calculate_dimensions(self._variables)
# mutable objects should not be hashable
# https://github.com/python/mypy/issues/4266
__hash__ = None # type: ignore[assignment]
def _all_compat(self, other: "Dataset", compat_str: str) -> bool:
"""Helper function for equals and identical"""
# some stores (e.g., scipy) do not seem to preserve order, so don't
# require matching order for equality
def compat(x: Variable, y: Variable) -> bool:
return getattr(x, compat_str)(y)
return self._coord_names == other._coord_names and utils.dict_equiv(
self._variables, other._variables, compat=compat
)
def broadcast_equals(self, other: "Dataset") -> bool:
"""Two Datasets are broadcast equal if they are equal after
broadcasting all variables against each other.
For example, variables that are scalar in one dataset but non-scalar in
the other dataset can still be broadcast equal if the the non-scalar
variable is a constant.
See Also
--------
Dataset.equals
Dataset.identical
"""
try:
return self._all_compat(other, "broadcast_equals")
except (TypeError, AttributeError):
return False
def equals(self, other: "Dataset") -> bool:
"""Two Datasets are equal if they have matching variables and
coordinates, all of which are equal.
Datasets can still be equal (like pandas objects) if they have NaN
values in the same locations.
This method is necessary because `v1 == v2` for ``Dataset``
does element-wise comparisons (like numpy.ndarrays).
See Also
--------
Dataset.broadcast_equals
Dataset.identical
"""
try:
return self._all_compat(other, "equals")
except (TypeError, AttributeError):
return False
def identical(self, other: "Dataset") -> bool:
"""Like equals, but also checks all dataset attributes and the
attributes on all variables and coordinates.
See Also
--------
Dataset.broadcast_equals
Dataset.equals
"""
try:
return utils.dict_equiv(self.attrs, other.attrs) and self._all_compat(
other, "identical"
)
except (TypeError, AttributeError):
return False
@property
def indexes(self) -> Indexes:
"""Mapping of pandas.Index objects used for label based indexing"""
if self._indexes is None:
self._indexes = default_indexes(self._variables, self._dims)
return Indexes(self._indexes)
@property
def coords(self) -> DatasetCoordinates:
"""Dictionary of xarray.DataArray objects corresponding to coordinate
variables
"""
return DatasetCoordinates(self)
@property
def data_vars(self) -> DataVariables:
"""Dictionary of DataArray objects corresponding to data variables"""
return DataVariables(self)
def set_coords(self, names: "Union[Hashable, Iterable[Hashable]]") -> "Dataset":
"""Given names of one or more variables, set them as coordinates
Parameters
----------
names : hashable or iterable of hashable
Name(s) of variables in this dataset to convert into coordinates.
Returns
-------
Dataset
See Also
--------
Dataset.swap_dims
"""
# TODO: allow inserting new coordinates with this method, like
# DataFrame.set_index?
# nb. check in self._variables, not self.data_vars to insure that the
# operation is idempotent
if isinstance(names, str) or not isinstance(names, Iterable):
names = [names]
else:
names = list(names)
self._assert_all_in_dataset(names)
obj = self.copy()
obj._coord_names.update(names)
return obj
def reset_coords(
self,
names: "Union[Hashable, Iterable[Hashable], None]" = None,
drop: bool = False,
) -> "Dataset":
"""Given names of coordinates, reset them to become variables
Parameters
----------
names : hashable or iterable of hashable, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By default, all non-index coordinates are reset.
drop : bool, optional
If True, remove coordinates instead of converting them into
variables.
Returns
-------
Dataset
"""
if names is None:
names = self._coord_names - set(self.dims)
else:
if isinstance(names, str) or not isinstance(names, Iterable):
names = [names]
else:
names = list(names)
self._assert_all_in_dataset(names)
bad_coords = set(names) & set(self.dims)
if bad_coords:
raise ValueError(
"cannot remove index coordinates with reset_coords: %s" % bad_coords
)
obj = self.copy()
obj._coord_names.difference_update(names)
if drop:
for name in names:
del obj._variables[name]
return obj
def dump_to_store(self, store: "AbstractDataStore", **kwargs) -> None:
"""Store dataset contents to a backends.*DataStore object."""
from ..backends.api import dump_to_store
# TODO: rename and/or cleanup this method to make it more consistent
# with to_netcdf()
dump_to_store(self, store, **kwargs)
def to_netcdf(
self,
path=None,
mode: str = "w",
format: str = None,
group: str = None,
engine: str = None,
encoding: Mapping = None,
unlimited_dims: Iterable[Hashable] = None,
compute: bool = True,
invalid_netcdf: bool = False,
) -> Union[bytes, "Delayed", None]:
"""Write dataset contents to a netCDF file.
Parameters
----------
path : str, Path or file-like, optional
Path to which to save this dataset. File-like objects are only
supported by the scipy engine. If no path is provided, this
function returns the resulting netCDF file as bytes; in this case,
we need to use scipy, which does not support netCDF version 4 (the
default format becomes NETCDF3_64BIT).
mode : {"w", "a"}, default: "w"
Write ('w') or append ('a') mode. If mode='w', any existing file at
this location will be overwritten. If mode='a', existing variables
will be overwritten.
format : {"NETCDF4", "NETCDF4_CLASSIC", "NETCDF3_64BIT", \
"NETCDF3_CLASSIC"}, optional
File format for the resulting netCDF file:
* NETCDF4: Data is stored in an HDF5 file, using netCDF4 API
features.
* NETCDF4_CLASSIC: Data is stored in an HDF5 file, using only
netCDF 3 compatible API features.
* NETCDF3_64BIT: 64-bit offset version of the netCDF 3 file format,
which fully supports 2+ GB files, but is only compatible with
clients linked against netCDF version 3.6.0 or later.
* NETCDF3_CLASSIC: The classic netCDF 3 file format. It does not
handle 2+ GB files very well.
All formats are supported by the netCDF4-python library.
scipy.io.netcdf only supports the last two formats.
The default format is NETCDF4 if you are saving a file to disk and
have the netCDF4-python library available. Otherwise, xarray falls
back to using scipy to write netCDF files and defaults to the
NETCDF3_64BIT format (scipy does not support netCDF4).
group : str, optional
Path to the netCDF4 group in the given file to open (only works for
format='NETCDF4'). The group(s) will be created if necessary.
engine : {"netcdf4", "scipy", "h5netcdf"}, optional
Engine to use when writing netCDF files. If not provided, the
default engine is chosen based on available dependencies, with a
preference for 'netcdf4' if writing to a file on disk.
encoding : dict, optional
Nested dictionary with variable names as keys and dictionaries of
variable specific encodings as values, e.g.,
``{"my_variable": {"dtype": "int16", "scale_factor": 0.1,
"zlib": True}, ...}``
The `h5netcdf` engine supports both the NetCDF4-style compression
encoding parameters ``{"zlib": True, "complevel": 9}`` and the h5py
ones ``{"compression": "gzip", "compression_opts": 9}``.
This allows using any compression plugin installed in the HDF5
library, e.g. LZF.
unlimited_dims : iterable of hashable, optional
Dimension(s) that should be serialized as unlimited dimensions.
By default, no dimensions are treated as unlimited dimensions.
Note that unlimited_dims may also be set via
``dataset.encoding["unlimited_dims"]``.
compute: bool, default: True
If true compute immediately, otherwise return a
``dask.delayed.Delayed`` object that can be computed later.
invalid_netcdf: bool, default: False
Only valid along with ``engine="h5netcdf"``. If True, allow writing
hdf5 files which are invalid netcdf as described in
https://github.com/shoyer/h5netcdf.
"""
if encoding is None:
encoding = {}
from ..backends.api import to_netcdf
return to_netcdf(
self,
path,
mode,
format=format,
group=group,
engine=engine,
encoding=encoding,
unlimited_dims=unlimited_dims,
compute=compute,
invalid_netcdf=invalid_netcdf,
)
def to_zarr(
self,
store: Union[MutableMapping, str, Path] = None,
chunk_store: Union[MutableMapping, str, Path] = None,
mode: str = None,
synchronizer=None,
group: str = None,
encoding: Mapping = None,
compute: bool = True,
consolidated: bool = False,
append_dim: Hashable = None,
region: Mapping[str, slice] = None,
) -> "ZarrStore":
"""Write dataset contents to a zarr group.
.. note:: Experimental
The Zarr backend is new and experimental. Please report any
unexpected behavior via github issues.
Parameters
----------
store : MutableMapping, str or Path, optional
Store or path to directory in file system.
chunk_store : MutableMapping, str or Path, optional
Store or path to directory in file system only for Zarr array chunks.
Requires zarr-python v2.4.0 or later.
mode : {"w", "w-", "a", None}, optional
Persistence mode: "w" means create (overwrite if exists);
"w-" means create (fail if exists);
"a" means override existing variables (create if does not exist).
If ``append_dim`` is set, ``mode`` can be omitted as it is
internally set to ``"a"``. Otherwise, ``mode`` will default to
`w-` if not set.
synchronizer : object, optional
Zarr array synchronizer.
group : str, optional
Group path. (a.k.a. `path` in zarr terminology.)
encoding : dict, optional
Nested dictionary with variable names as keys and dictionaries of
variable specific encodings as values, e.g.,
``{"my_variable": {"dtype": "int16", "scale_factor": 0.1,}, ...}``
compute : bool, optional
If True write array data immediately, otherwise return a
``dask.delayed.Delayed`` object that can be computed to write
array data later. Metadata is always updated eagerly.
consolidated : bool, optional
If True, apply zarr's `consolidate_metadata` function to the store
after writing metadata.
append_dim : hashable, optional
If set, the dimension along which the data will be appended. All
other dimensions on overriden variables must remain the same size.
region : dict, optional
Optional mapping from dimension names to integer slices along
dataset dimensions to indicate the region of existing zarr array(s)
in which to write this dataset's data. For example,
``{'x': slice(0, 1000), 'y': slice(10000, 11000)}`` would indicate
that values should be written to the region ``0:1000`` along ``x``
and ``10000:11000`` along ``y``.
Two restrictions apply to the use of ``region``:
- If ``region`` is set, _all_ variables in a dataset must have at
least one dimension in common with the region. Other variables
should be written in a separate call to ``to_zarr()``.
- Dimensions cannot be included in both ``region`` and
``append_dim`` at the same time. To create empty arrays to fill
in with ``region``, use a separate call to ``to_zarr()`` with
``compute=False``. See "Appending to existing Zarr stores" in
the reference documentation for full details.
References
----------
https://zarr.readthedocs.io/
Notes
-----
Zarr chunking behavior:
If chunks are found in the encoding argument or attribute
corresponding to any DataArray, those chunks are used.
If a DataArray is a dask array, it is written with those chunks.
If not other chunks are found, Zarr uses its own heuristics to
choose automatic chunk sizes.
"""
from ..backends.api import to_zarr
if encoding is None:
encoding = {}
return to_zarr(
self,
store=store,
chunk_store=chunk_store,
mode=mode,
synchronizer=synchronizer,
group=group,
encoding=encoding,
compute=compute,
consolidated=consolidated,
append_dim=append_dim,
region=region,
)
def __repr__(self) -> str:
return formatting.dataset_repr(self)
def _repr_html_(self):
if OPTIONS["display_style"] == "text":
return f"<pre>{escape(repr(self))}</pre>"
return formatting_html.dataset_repr(self)
def info(self, buf=None) -> None:
"""
Concise summary of a Dataset variables and attributes.
Parameters
----------
buf : file-like, default: sys.stdout
writable buffer
See Also
--------
pandas.DataFrame.assign
ncdump : netCDF's ncdump
"""
if buf is None: # pragma: no cover
buf = sys.stdout
lines = []
lines.append("xarray.Dataset {")
lines.append("dimensions:")
for name, size in self.dims.items():
lines.append(f"\t{name} = {size} ;")
lines.append("\nvariables:")
for name, da in self.variables.items():
dims = ", ".join(da.dims)
lines.append(f"\t{da.dtype} {name}({dims}) ;")
for k, v in da.attrs.items():
lines.append(f"\t\t{name}:{k} = {v} ;")
lines.append("\n// global attributes:")
for k, v in self.attrs.items():
lines.append(f"\t:{k} = {v} ;")
lines.append("}")
buf.write("\n".join(lines))
@property
def chunks(self) -> Mapping[Hashable, Tuple[int, ...]]:
"""Block dimensions for this dataset's data or None if it's not a dask
array.
"""
chunks: Dict[Hashable, Tuple[int, ...]] = {}
for v in self.variables.values():
if v.chunks is not None:
for dim, c in zip(v.dims, v.chunks):
if dim in chunks and c != chunks[dim]:
raise ValueError(
f"Object has inconsistent chunks along dimension {dim}. "
"This can be fixed by calling unify_chunks()."
)
chunks[dim] = c
return Frozen(SortedKeysDict(chunks))
def chunk(
self,
chunks: Union[
Number,
str,
Mapping[Hashable, Union[None, Number, str, Tuple[Number, ...]]],
] = {}, # {} even though it's technically unsafe, is being used intentionally here (#4667)
name_prefix: str = "xarray-",
token: str = None,
lock: bool = False,
) -> "Dataset":
"""Coerce all arrays in this dataset into dask arrays with the given
chunks.
Non-dask arrays in this dataset will be converted to dask arrays. Dask
arrays will be rechunked to the given chunk sizes.
If neither chunks is not provided for one or more dimensions, chunk
sizes along that dimension will not be updated; non-dask arrays will be
converted into dask arrays with a single block.
Parameters
----------
chunks : int, 'auto' or mapping, optional
Chunk sizes along each dimension, e.g., ``5`` or
``{"x": 5, "y": 5}``.
name_prefix : str, optional
Prefix for the name of any new dask arrays.
token : str, optional
Token uniquely identifying this dataset.
lock : optional
Passed on to :py:func:`dask.array.from_array`, if the array is not
already as dask array.
Returns
-------
chunked : xarray.Dataset
"""
if chunks is None:
warnings.warn(
"None value for 'chunks' is deprecated. "
"It will raise an error in the future. Use instead '{}'",
category=FutureWarning,
)
chunks = {}
if isinstance(chunks, (Number, str)):
chunks = dict.fromkeys(self.dims, chunks)
bad_dims = chunks.keys() - self.dims.keys()
if bad_dims:
raise ValueError(
"some chunks keys are not dimensions on this " "object: %s" % bad_dims
)
variables = {
k: _maybe_chunk(k, v, chunks, token, lock, name_prefix)
for k, v in self.variables.items()
}
return self._replace(variables)
def _validate_indexers(
self, indexers: Mapping[Hashable, Any], missing_dims: str = "raise"
) -> Iterator[Tuple[Hashable, Union[int, slice, np.ndarray, Variable]]]:
"""Here we make sure
+ indexer has a valid keys
+ indexer is in a valid data type
+ string indexers are cast to the appropriate date type if the
associated index is a DatetimeIndex or CFTimeIndex
"""
from .dataarray import DataArray
indexers = drop_dims_from_indexers(indexers, self.dims, missing_dims)
# all indexers should be int, slice, np.ndarrays, or Variable
for k, v in indexers.items():
if isinstance(v, (int, slice, Variable)):
yield k, v
elif isinstance(v, DataArray):
yield k, v.variable
elif isinstance(v, tuple):
yield k, as_variable(v)
elif isinstance(v, Dataset):
raise TypeError("cannot use a Dataset as an indexer")
elif isinstance(v, Sequence) and len(v) == 0:
yield k, np.empty((0,), dtype="int64")
else:
v = np.asarray(v)
if v.dtype.kind in "US":
index = self.indexes[k]
if isinstance(index, pd.DatetimeIndex):
v = v.astype("datetime64[ns]")
elif isinstance(index, xr.CFTimeIndex):
v = _parse_array_of_cftime_strings(v, index.date_type)
if v.ndim > 1:
raise IndexError(
"Unlabeled multi-dimensional array cannot be "
"used for indexing: {}".format(k)
)
yield k, v
def _validate_interp_indexers(
self, indexers: Mapping[Hashable, Any]
) -> Iterator[Tuple[Hashable, Variable]]:
"""Variant of _validate_indexers to be used for interpolation"""
for k, v in self._validate_indexers(indexers):
if isinstance(v, Variable):
if v.ndim == 1:
yield k, v.to_index_variable()
else:
yield k, v
elif isinstance(v, int):
yield k, Variable((), v)
elif isinstance(v, np.ndarray):
if v.ndim == 0:
yield k, Variable((), v)
elif v.ndim == 1:
yield k, IndexVariable((k,), v)
else:
raise AssertionError() # Already tested by _validate_indexers
else:
raise TypeError(type(v))
def _get_indexers_coords_and_indexes(self, indexers):
"""Extract coordinates and indexes from indexers.
Only coordinate with a name different from any of self.variables will
be attached.
"""
from .dataarray import DataArray
coords_list = []
for k, v in indexers.items():
if isinstance(v, DataArray):
if v.dtype.kind == "b":
if v.ndim != 1: # we only support 1-d boolean array
raise ValueError(
"{:d}d-boolean array is used for indexing along "
"dimension {!r}, but only 1d boolean arrays are "
"supported.".format(v.ndim, k)
)
# Make sure in case of boolean DataArray, its
# coordinate also should be indexed.
v_coords = v[v.values.nonzero()[0]].coords
else:
v_coords = v.coords
coords_list.append(v_coords)
# we don't need to call align() explicitly or check indexes for
# alignment, because merge_variables already checks for exact alignment
# between dimension coordinates
coords, indexes = merge_coordinates_without_align(coords_list)
assert_coordinate_consistent(self, coords)
# silently drop the conflicted variables.
attached_coords = {k: v for k, v in coords.items() if k not in self._variables}
attached_indexes = {
k: v for k, v in indexes.items() if k not in self._variables
}
return attached_coords, attached_indexes
def isel(
self,
indexers: Mapping[Hashable, Any] = None,
drop: bool = False,
missing_dims: str = "raise",
**indexers_kwargs: Any,
) -> "Dataset":
"""Returns a new dataset with each array indexed along the specified
dimension(s).
This method selects values from each array using its `__getitem__`
method, except this method does not require knowing the order of
each array's dimensions.
Parameters
----------
indexers : dict, optional
A dict with keys matching dimensions and values given
by integers, slice objects or arrays.
indexer can be a integer, slice, array-like or DataArray.
If DataArrays are passed as indexers, xarray-style indexing will be
carried out. See :ref:`indexing` for the details.
One of indexers or indexers_kwargs must be provided.
drop : bool, optional
If ``drop=True``, drop coordinates variables indexed by integers
instead of making them scalar.
missing_dims : {"raise", "warn", "ignore"}, default: "raise"
What to do if dimensions that should be selected from are not present in the
Dataset:
- "raise": raise an exception
- "warning": raise a warning, and ignore the missing dimensions
- "ignore": ignore the missing dimensions
**indexers_kwargs : {dim: indexer, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
Returns
-------
obj : Dataset
A new Dataset with the same contents as this dataset, except each
array and dimension is indexed by the appropriate indexers.
If indexer DataArrays have coordinates that do not conflict with
this object, then these coordinates will be attached.
In general, each array's data will be a view of the array's data
in this dataset, unless vectorized indexing was triggered by using
an array indexer, in which case the data will be a copy.
See Also
--------
Dataset.sel
DataArray.isel
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "isel")
if any(is_fancy_indexer(idx) for idx in indexers.values()):
return self._isel_fancy(indexers, drop=drop, missing_dims=missing_dims)
# Much faster algorithm for when all indexers are ints, slices, one-dimensional
# lists, or zero or one-dimensional np.ndarray's
indexers = drop_dims_from_indexers(indexers, self.dims, missing_dims)
variables = {}
dims: Dict[Hashable, Tuple[int, ...]] = {}
coord_names = self._coord_names.copy()
indexes = self._indexes.copy() if self._indexes is not None else None
for var_name, var_value in self._variables.items():
var_indexers = {k: v for k, v in indexers.items() if k in var_value.dims}
if var_indexers:
var_value = var_value.isel(var_indexers)
if drop and var_value.ndim == 0 and var_name in coord_names:
coord_names.remove(var_name)
if indexes:
indexes.pop(var_name, None)
continue
if indexes and var_name in indexes:
if var_value.ndim == 1:
indexes[var_name] = var_value.to_index()
else:
del indexes[var_name]
variables[var_name] = var_value
dims.update(zip(var_value.dims, var_value.shape))
return self._construct_direct(
variables=variables,
coord_names=coord_names,
dims=dims,
attrs=self._attrs,
indexes=indexes,
encoding=self._encoding,
close=self._close,
)
def _isel_fancy(
self,
indexers: Mapping[Hashable, Any],
*,
drop: bool,
missing_dims: str = "raise",
) -> "Dataset":
# Note: we need to preserve the original indexers variable in order to merge the
# coords below
indexers_list = list(self._validate_indexers(indexers, missing_dims))
variables: Dict[Hashable, Variable] = {}
indexes: Dict[Hashable, pd.Index] = {}
for name, var in self.variables.items():
var_indexers = {k: v for k, v in indexers_list if k in var.dims}
if drop and name in var_indexers:
continue # drop this variable
if name in self.indexes:
new_var, new_index = isel_variable_and_index(
name, var, self.indexes[name], var_indexers
)
if new_index is not None:
indexes[name] = new_index
elif var_indexers:
new_var = var.isel(indexers=var_indexers)
else:
new_var = var.copy(deep=False)
variables[name] = new_var
coord_names = self._coord_names & variables.keys()
selected = self._replace_with_new_dims(variables, coord_names, indexes)
# Extract coordinates from indexers
coord_vars, new_indexes = selected._get_indexers_coords_and_indexes(indexers)
variables.update(coord_vars)
indexes.update(new_indexes)
coord_names = self._coord_names & variables.keys() | coord_vars.keys()
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def sel(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
drop: bool = False,
**indexers_kwargs: Any,
) -> "Dataset":
"""Returns a new dataset with each array indexed by tick labels
along the specified dimension(s).
In contrast to `Dataset.isel`, indexers for this method should use
labels instead of integers.
Under the hood, this method is powered by using pandas's powerful Index
objects. This makes label based indexing essentially just as fast as
using integer indexing.
It also means this method uses pandas's (well documented) logic for
indexing. This means you can use string shortcuts for datetime indexes
(e.g., '2000-01' to select all values in January 2000). It also means
that slices are treated as inclusive of both the start and stop values,
unlike normal Python indexing.
Parameters
----------
indexers : dict, optional
A dict with keys matching dimensions and values given
by scalars, slices or arrays of tick labels. For dimensions with
multi-index, the indexer may also be a dict-like object with keys
matching index level names.
If DataArrays are passed as indexers, xarray-style indexing will be
carried out. See :ref:`indexing` for the details.
One of indexers or indexers_kwargs must be provided.
method : {None, "nearest", "pad", "ffill", "backfill", "bfill"}, optional
Method to use for inexact matches:
* None (default): only exact matches
* pad / ffill: propagate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value
tolerance : optional
Maximum distance between original and new labels for inexact
matches. The values of the index at the matching locations must
satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
drop : bool, optional
If ``drop=True``, drop coordinates variables in `indexers` instead
of making them scalar.
**indexers_kwargs : {dim: indexer, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
Returns
-------
obj : Dataset
A new Dataset with the same contents as this dataset, except each
variable and dimension is indexed by the appropriate indexers.
If indexer DataArrays have coordinates that do not conflict with
this object, then these coordinates will be attached.
In general, each array's data will be a view of the array's data
in this dataset, unless vectorized indexing was triggered by using
an array indexer, in which case the data will be a copy.
See Also
--------
Dataset.isel
DataArray.sel
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "sel")
pos_indexers, new_indexes = remap_label_indexers(
self, indexers=indexers, method=method, tolerance=tolerance
)
result = self.isel(indexers=pos_indexers, drop=drop)
return result._overwrite_indexes(new_indexes)
def head(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
"""Returns a new dataset with the first `n` values of each array
for the specified dimension(s).
Parameters
----------
indexers : dict or int, default: 5
A dict with keys matching dimensions and integer values `n`
or a single integer `n` applied over all dimensions.
One of indexers or indexers_kwargs must be provided.
**indexers_kwargs : {dim: n, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
See Also
--------
Dataset.tail
Dataset.thin
DataArray.head
"""
if not indexers_kwargs:
if indexers is None:
indexers = 5
if not isinstance(indexers, int) and not is_dict_like(indexers):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "head")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
indexers_slices = {k: slice(val) for k, val in indexers.items()}
return self.isel(indexers_slices)
def tail(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
"""Returns a new dataset with the last `n` values of each array
for the specified dimension(s).
Parameters
----------
indexers : dict or int, default: 5
A dict with keys matching dimensions and integer values `n`
or a single integer `n` applied over all dimensions.
One of indexers or indexers_kwargs must be provided.
**indexers_kwargs : {dim: n, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
See Also
--------
Dataset.head
Dataset.thin
DataArray.tail
"""
if not indexers_kwargs:
if indexers is None:
indexers = 5
if not isinstance(indexers, int) and not is_dict_like(indexers):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "tail")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
indexers_slices = {
k: slice(-val, None) if val != 0 else slice(val)
for k, val in indexers.items()
}
return self.isel(indexers_slices)
def thin(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
"""Returns a new dataset with each array indexed along every `n`-th
value for the specified dimension(s)
Parameters
----------
indexers : dict or int
A dict with keys matching dimensions and integer values `n`
or a single integer `n` applied over all dimensions.
One of indexers or indexers_kwargs must be provided.
**indexers_kwargs : {dim: n, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
See Also
--------
Dataset.head
Dataset.tail
DataArray.thin
"""
if (
not indexers_kwargs
and not isinstance(indexers, int)
and not is_dict_like(indexers)
):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "thin")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
elif v == 0:
raise ValueError("step cannot be zero")
indexers_slices = {k: slice(None, None, val) for k, val in indexers.items()}
return self.isel(indexers_slices)
def broadcast_like(
self, other: Union["Dataset", "DataArray"], exclude: Iterable[Hashable] = None
) -> "Dataset":
"""Broadcast this DataArray against another Dataset or DataArray.
This is equivalent to xr.broadcast(other, self)[1]
Parameters
----------
other : Dataset or DataArray
Object against which to broadcast this array.
exclude : iterable of hashable, optional
Dimensions that must not be broadcasted
"""
if exclude is None:
exclude = set()
else:
exclude = set(exclude)
args = align(other, self, join="outer", copy=False, exclude=exclude)
dims_map, common_coords = _get_broadcast_dims_map_common_coords(args, exclude)
return _broadcast_helper(args[1], exclude, dims_map, common_coords)
def reindex_like(
self,
other: Union["Dataset", "DataArray"],
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
) -> "Dataset":
"""Conform this object onto the indexes of another object, filling in
missing values with ``fill_value``. The default fill value is NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mapping from dimension
names to pandas.Index objects, which provides coordinates upon
which to index the variables in this dataset. The indexes on this
other object need not be the same as the indexes on this
dataset. Any mis-matched index values will be filled in with
NaN, and any mis-matched dimension names will simply be ignored.
method : {None, "nearest", "pad", "ffill", "backfill", "bfill"}, optional
Method to use for filling index values from other not found in this
dataset:
* None (default): don't fill gaps
* pad / ffill: propagate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value
tolerance : optional
Maximum distance between original and new labels for inexact
matches. The values of the index at the matching locations must
satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
copy : bool, optional
If ``copy=True``, data in the return value is always copied. If
``copy=False`` and reindexing is unnecessary, or can be performed
with only slice operations, then the output may share memory with
the input. In either case, a new xarray object is always returned.
fill_value : scalar or dict-like, optional
Value to use for newly missing values. If a dict-like maps
variable names to fill values.
Returns
-------
reindexed : Dataset
Another dataset, with this dataset's data but coordinates from the
other object.
See Also
--------
Dataset.reindex
align
"""
indexers = alignment.reindex_like_indexers(self, other)
return self.reindex(
indexers=indexers,
method=method,
copy=copy,
fill_value=fill_value,
tolerance=tolerance,
)
def reindex(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
**indexers_kwargs: Any,
) -> "Dataset":
"""Conform this object onto a new set of indexes, filling in
missing values with ``fill_value``. The default fill value is NaN.
Parameters
----------
indexers : dict, optional
Dictionary with keys given by dimension names and values given by
arrays of coordinates tick labels. Any mis-matched coordinate
values will be filled in with NaN, and any mis-matched dimension
names will simply be ignored.
One of indexers or indexers_kwargs must be provided.
method : {None, "nearest", "pad", "ffill", "backfill", "bfill"}, optional
Method to use for filling index values in ``indexers`` not found in
this dataset:
* None (default): don't fill gaps
* pad / ffill: propagate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value
tolerance : optional
Maximum distance between original and new labels for inexact
matches. The values of the index at the matching locations must
satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
copy : bool, optional
If ``copy=True``, data in the return value is always copied. If
``copy=False`` and reindexing is unnecessary, or can be performed
with only slice operations, then the output may share memory with
the input. In either case, a new xarray object is always returned.
fill_value : scalar or dict-like, optional
Value to use for newly missing values. If a dict-like,
maps variable names (including coordinates) to fill values.
sparse : bool, default: False
use sparse-array.
**indexers_kwargs : {dim: indexer, ...}, optional
Keyword arguments in the same form as ``indexers``.
One of indexers or indexers_kwargs must be provided.
Returns
-------
reindexed : Dataset
Another dataset, with this dataset's data but replaced coordinates.
See Also
--------
Dataset.reindex_like
align
pandas.Index.get_indexer
Examples
--------
Create a dataset with some fictional data.
>>> import xarray as xr
>>> import pandas as pd
>>> x = xr.Dataset(
... {
... "temperature": ("station", 20 * np.random.rand(4)),
... "pressure": ("station", 500 * np.random.rand(4)),
... },
... coords={"station": ["boston", "nyc", "seattle", "denver"]},
... )
>>> x
<xarray.Dataset>
Dimensions: (station: 4)
Coordinates:
* station (station) <U7 'boston' 'nyc' 'seattle' 'denver'
Data variables:
temperature (station) float64 10.98 14.3 12.06 10.9
pressure (station) float64 211.8 322.9 218.8 445.9
>>> x.indexes
station: Index(['boston', 'nyc', 'seattle', 'denver'], dtype='object', name='station')
Create a new index and reindex the dataset. By default values in the new index that
do not have corresponding records in the dataset are assigned `NaN`.
>>> new_index = ["boston", "austin", "seattle", "lincoln"]
>>> x.reindex({"station": new_index})
<xarray.Dataset>
Dimensions: (station: 4)
Coordinates:
* station (station) <U7 'boston' 'austin' 'seattle' 'lincoln'
Data variables:
temperature (station) float64 10.98 nan 12.06 nan
pressure (station) float64 211.8 nan 218.8 nan
We can fill in the missing values by passing a value to the keyword `fill_value`.
>>> x.reindex({"station": new_index}, fill_value=0)
<xarray.Dataset>
Dimensions: (station: 4)
Coordinates:
* station (station) <U7 'boston' 'austin' 'seattle' 'lincoln'
Data variables:
temperature (station) float64 10.98 0.0 12.06 0.0
pressure (station) float64 211.8 0.0 218.8 0.0
We can also use different fill values for each variable.
>>> x.reindex(
... {"station": new_index}, fill_value={"temperature": 0, "pressure": 100}
... )
<xarray.Dataset>
Dimensions: (station: 4)
Coordinates:
* station (station) <U7 'boston' 'austin' 'seattle' 'lincoln'
Data variables:
temperature (station) float64 10.98 0.0 12.06 0.0
pressure (station) float64 211.8 100.0 218.8 100.0
Because the index is not monotonically increasing or decreasing, we cannot use arguments
to the keyword method to fill the `NaN` values.
>>> x.reindex({"station": new_index}, method="nearest")
Traceback (most recent call last):
...
raise ValueError('index must be monotonic increasing or decreasing')
ValueError: index must be monotonic increasing or decreasing
To further illustrate the filling functionality in reindex, we will create a
dataset with a monotonically increasing index (for example, a sequence of dates).
>>> x2 = xr.Dataset(
... {
... "temperature": (
... "time",
... [15.57, 12.77, np.nan, 0.3081, 16.59, 15.12],
... ),
... "pressure": ("time", 500 * np.random.rand(6)),
... },
... coords={"time": pd.date_range("01/01/2019", periods=6, freq="D")},
... )
>>> x2
<xarray.Dataset>
Dimensions: (time: 6)
Coordinates:
* time (time) datetime64[ns] 2019-01-01 2019-01-02 ... 2019-01-06
Data variables:
temperature (time) float64 15.57 12.77 nan 0.3081 16.59 15.12
pressure (time) float64 481.8 191.7 395.9 264.4 284.0 462.8
Suppose we decide to expand the dataset to cover a wider date range.
>>> time_index2 = pd.date_range("12/29/2018", periods=10, freq="D")
>>> x2.reindex({"time": time_index2})
<xarray.Dataset>
Dimensions: (time: 10)
Coordinates:
* time (time) datetime64[ns] 2018-12-29 2018-12-30 ... 2019-01-07
Data variables:
temperature (time) float64 nan nan nan 15.57 ... 0.3081 16.59 15.12 nan
pressure (time) float64 nan nan nan 481.8 ... 264.4 284.0 462.8 nan
The index entries that did not have a value in the original data frame (for example, `2018-12-29`)
are by default filled with NaN. If desired, we can fill in the missing values using one of several options.
For example, to back-propagate the last valid value to fill the `NaN` values,
pass `bfill` as an argument to the `method` keyword.
>>> x3 = x2.reindex({"time": time_index2}, method="bfill")
>>> x3
<xarray.Dataset>
Dimensions: (time: 10)
Coordinates:
* time (time) datetime64[ns] 2018-12-29 2018-12-30 ... 2019-01-07
Data variables:
temperature (time) float64 15.57 15.57 15.57 15.57 ... 16.59 15.12 nan
pressure (time) float64 481.8 481.8 481.8 481.8 ... 284.0 462.8 nan
Please note that the `NaN` value present in the original dataset (at index value `2019-01-03`)
will not be filled by any of the value propagation schemes.
>>> x2.where(x2.temperature.isnull(), drop=True)
<xarray.Dataset>
Dimensions: (time: 1)
Coordinates:
* time (time) datetime64[ns] 2019-01-03
Data variables:
temperature (time) float64 nan
pressure (time) float64 395.9
>>> x3.where(x3.temperature.isnull(), drop=True)
<xarray.Dataset>
Dimensions: (time: 2)
Coordinates:
* time (time) datetime64[ns] 2019-01-03 2019-01-07
Data variables:
temperature (time) float64 nan nan
pressure (time) float64 395.9 nan
This is because filling while reindexing does not look at dataset values, but only compares
the original and desired indexes. If you do want to fill in the `NaN` values present in the
original dataset, use the :py:meth:`~Dataset.fillna()` method.
"""
return self._reindex(
indexers,
method,
tolerance,
copy,
fill_value,
sparse=False,
**indexers_kwargs,
)
def _reindex(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
sparse: bool = False,
**indexers_kwargs: Any,
) -> "Dataset":
"""
same to _reindex but support sparse option
"""
indexers = utils.either_dict_or_kwargs(indexers, indexers_kwargs, "reindex")
bad_dims = [d for d in indexers if d not in self.dims]
if bad_dims:
raise ValueError("invalid reindex dimensions: %s" % bad_dims)
variables, indexes = alignment.reindex_variables(
self.variables,
self.sizes,
self.indexes,
indexers,
method,
tolerance,
copy=copy,
fill_value=fill_value,
sparse=sparse,
)
coord_names = set(self._coord_names)
coord_names.update(indexers)
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def interp(
self,
coords: Mapping[Hashable, Any] = None,
method: str = "linear",
assume_sorted: bool = False,
kwargs: Mapping[str, Any] = None,
**coords_kwargs: Any,
) -> "Dataset":
"""Multidimensional interpolation of Dataset.
Parameters
----------
coords : dict, optional
Mapping from dimension names to the new coordinates.
New coordinate can be a scalar, array-like or DataArray.
If DataArrays are passed as new coordinates, their dimensions are
used for the broadcasting. Missing values are skipped.
method : str, optional
{"linear", "nearest"} for multidimensional array,
{"linear", "nearest", "zero", "slinear", "quadratic", "cubic"}
for 1-dimensional array. "linear" is used by default.
assume_sorted : bool, optional
If False, values of coordinates that are interpolated over can be
in any order and they are sorted first. If True, interpolated
coordinates are assumed to be an array of monotonically increasing
values.
kwargs : dict, optional
Additional keyword arguments passed to scipy's interpolator. Valid
options and their behavior depend on if 1-dimensional or
multi-dimensional interpolation is used.
**coords_kwargs : {dim: coordinate, ...}, optional
The keyword arguments form of ``coords``.
One of coords or coords_kwargs must be provided.
Returns
-------
interpolated : Dataset
New dataset on the new coordinates.
Notes
-----
scipy is required.
See Also
--------
scipy.interpolate.interp1d
scipy.interpolate.interpn
Examples
--------
>>> ds = xr.Dataset(
... data_vars={
... "a": ("x", [5, 7, 4]),
... "b": (
... ("x", "y"),
... [[1, 4, 2, 9], [2, 7, 6, np.nan], [6, np.nan, 5, 8]],
... ),
... },
... coords={"x": [0, 1, 2], "y": [10, 12, 14, 16]},
... )
>>> ds
<xarray.Dataset>
Dimensions: (x: 3, y: 4)
Coordinates:
* x (x) int64 0 1 2
* y (y) int64 10 12 14 16
Data variables:
a (x) int64 5 7 4
b (x, y) float64 1.0 4.0 2.0 9.0 2.0 7.0 6.0 nan 6.0 nan 5.0 8.0
1D interpolation with the default method (linear):
>>> ds.interp(x=[0, 0.75, 1.25, 1.75])
<xarray.Dataset>
Dimensions: (x: 4, y: 4)
Coordinates:
* y (y) int64 10 12 14 16
* x (x) float64 0.0 0.75 1.25 1.75
Data variables:
a (x) float64 5.0 6.5 6.25 4.75
b (x, y) float64 1.0 4.0 2.0 nan 1.75 6.25 ... nan 5.0 nan 5.25 nan
1D interpolation with a different method:
>>> ds.interp(x=[0, 0.75, 1.25, 1.75], method="nearest")
<xarray.Dataset>
Dimensions: (x: 4, y: 4)
Coordinates:
* y (y) int64 10 12 14 16
* x (x) float64 0.0 0.75 1.25 1.75
Data variables:
a (x) float64 5.0 7.0 7.0 4.0
b (x, y) float64 1.0 4.0 2.0 9.0 2.0 7.0 ... 6.0 nan 6.0 nan 5.0 8.0
1D extrapolation:
>>> ds.interp(
... x=[1, 1.5, 2.5, 3.5],
... method="linear",
... kwargs={"fill_value": "extrapolate"},
... )
<xarray.Dataset>
Dimensions: (x: 4, y: 4)
Coordinates:
* y (y) int64 10 12 14 16
* x (x) float64 1.0 1.5 2.5 3.5
Data variables:
a (x) float64 7.0 5.5 2.5 -0.5
b (x, y) float64 2.0 7.0 6.0 nan 4.0 nan ... 4.5 nan 12.0 nan 3.5 nan
2D interpolation:
>>> ds.interp(x=[0, 0.75, 1.25, 1.75], y=[11, 13, 15], method="linear")
<xarray.Dataset>
Dimensions: (x: 4, y: 3)
Coordinates:
* x (x) float64 0.0 0.75 1.25 1.75
* y (y) int64 11 13 15
Data variables:
a (x) float64 5.0 6.5 6.25 4.75
b (x, y) float64 2.5 3.0 nan 4.0 5.625 nan nan nan nan nan nan nan
"""
from . import missing
if kwargs is None:
kwargs = {}
coords = either_dict_or_kwargs(coords, coords_kwargs, "interp")
indexers = dict(self._validate_interp_indexers(coords))
if coords:
# This avoids broadcasting over coordinates that are both in
# the original array AND in the indexing array. It essentially
# forces interpolation along the shared coordinates.
sdims = (
set(self.dims)
.intersection(*[set(nx.dims) for nx in indexers.values()])
.difference(coords.keys())
)
indexers.update({d: self.variables[d] for d in sdims})
obj = self if assume_sorted else self.sortby([k for k in coords])
def maybe_variable(obj, k):
# workaround to get variable for dimension without coordinate.
try:
return obj._variables[k]
except KeyError:
return as_variable((k, range(obj.dims[k])))
def _validate_interp_indexer(x, new_x):
# In the case of datetimes, the restrictions placed on indexers
# used with interp are stronger than those which are placed on
# isel, so we need an additional check after _validate_indexers.
if _contains_datetime_like_objects(
x
) and not _contains_datetime_like_objects(new_x):
raise TypeError(
"When interpolating over a datetime-like "
"coordinate, the coordinates to "
"interpolate to must be either datetime "
"strings or datetimes. "
"Instead got\n{}".format(new_x)
)
return x, new_x
variables: Dict[Hashable, Variable] = {}
for name, var in obj._variables.items():
if name in indexers:
continue
if var.dtype.kind in "uifc":
var_indexers = {
k: _validate_interp_indexer(maybe_variable(obj, k), v)
for k, v in indexers.items()
if k in var.dims
}
variables[name] = missing.interp(var, var_indexers, method, **kwargs)
elif all(d not in indexers for d in var.dims):
# keep unrelated object array
variables[name] = var
coord_names = obj._coord_names & variables.keys()
indexes = {k: v for k, v in obj.indexes.items() if k not in indexers}
selected = self._replace_with_new_dims(
variables.copy(), coord_names, indexes=indexes
)
# attach indexer as coordinate
variables.update(indexers)
for k, v in indexers.items():
assert isinstance(v, Variable)
if v.dims == (k,):
indexes[k] = v.to_index()
# Extract coordinates from indexers
coord_vars, new_indexes = selected._get_indexers_coords_and_indexes(coords)
variables.update(coord_vars)
indexes.update(new_indexes)
coord_names = obj._coord_names & variables.keys() | coord_vars.keys()
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def interp_like(
self,
other: Union["Dataset", "DataArray"],
method: str = "linear",
assume_sorted: bool = False,
kwargs: Mapping[str, Any] = None,
) -> "Dataset":
"""Interpolate this object onto the coordinates of another object,
filling the out of range values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mapping from dimension
names to an 1d array-like, which provides coordinates upon
which to index the variables in this dataset. Missing values are skipped.
method : str, optional
{"linear", "nearest"} for multidimensional array,
{"linear", "nearest", "zero", "slinear", "quadratic", "cubic"}
for 1-dimensional array. 'linear' is used by default.
assume_sorted : bool, optional
If False, values of coordinates that are interpolated over can be
in any order and they are sorted first. If True, interpolated
coordinates are assumed to be an array of monotonically increasing
values.
kwargs : dict, optional
Additional keyword passed to scipy's interpolator.
Returns
-------
interpolated : Dataset
Another dataset by interpolating this dataset's data along the
coordinates of the other object.
Notes
-----
scipy is required.
If the dataset has object-type coordinates, reindex is used for these
coordinates instead of the interpolation.
See Also
--------
Dataset.interp
Dataset.reindex_like
"""
if kwargs is None:
kwargs = {}
coords = alignment.reindex_like_indexers(self, other)
numeric_coords: Dict[Hashable, pd.Index] = {}
object_coords: Dict[Hashable, pd.Index] = {}
for k, v in coords.items():
if v.dtype.kind in "uifcMm":
numeric_coords[k] = v
else:
object_coords[k] = v
ds = self
if object_coords:
# We do not support interpolation along object coordinate.
# reindex instead.
ds = self.reindex(object_coords)
return ds.interp(numeric_coords, method, assume_sorted, kwargs)
# Helper methods for rename()
def _rename_vars(self, name_dict, dims_dict):
variables = {}
coord_names = set()
for k, v in self.variables.items():
var = v.copy(deep=False)
var.dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
name = name_dict.get(k, k)
if name in variables:
raise ValueError(f"the new name {name!r} conflicts")
variables[name] = var
if k in self._coord_names:
coord_names.add(name)
return variables, coord_names
def _rename_dims(self, name_dict):
return {name_dict.get(k, k): v for k, v in self.dims.items()}
def _rename_indexes(self, name_dict, dims_set):
if self._indexes is None:
return None
indexes = {}
for k, v in self.indexes.items():
new_name = name_dict.get(k, k)
if new_name not in dims_set:
continue
if isinstance(v, pd.MultiIndex):
new_names = [name_dict.get(k, k) for k in v.names]
index = v.rename(names=new_names)
else:
index = v.rename(new_name)
indexes[new_name] = index
return indexes
def _rename_all(self, name_dict, dims_dict):
variables, coord_names = self._rename_vars(name_dict, dims_dict)
dims = self._rename_dims(dims_dict)
indexes = self._rename_indexes(name_dict, dims.keys())
return variables, coord_names, dims, indexes
def rename(
self,
name_dict: Mapping[Hashable, Hashable] = None,
**names: Hashable,
) -> "Dataset":
"""Returns a new object with renamed variables and dimensions.
Parameters
----------
name_dict : dict-like, optional
Dictionary whose keys are current variable or dimension names and
whose values are the desired names.
**names : optional
Keyword form of ``name_dict``.
One of name_dict or names must be provided.
Returns
-------
renamed : Dataset
Dataset with renamed variables and dimensions.
See Also
--------
Dataset.swap_dims
Dataset.rename_vars
Dataset.rename_dims
DataArray.rename
"""
name_dict = either_dict_or_kwargs(name_dict, names, "rename")
for k in name_dict.keys():
if k not in self and k not in self.dims:
raise ValueError(
"cannot rename %r because it is not a "
"variable or dimension in this dataset" % k
)
variables, coord_names, dims, indexes = self._rename_all(
name_dict=name_dict, dims_dict=name_dict
)
assert_unique_multiindex_level_names(variables)
return self._replace(variables, coord_names, dims=dims, indexes=indexes)
def rename_dims(
self, dims_dict: Mapping[Hashable, Hashable] = None, **dims: Hashable
) -> "Dataset":
"""Returns a new object with renamed dimensions only.
Parameters
----------
dims_dict : dict-like, optional
Dictionary whose keys are current dimension names and
whose values are the desired names. The desired names must
not be the name of an existing dimension or Variable in the Dataset.
**dims : optional
Keyword form of ``dims_dict``.
One of dims_dict or dims must be provided.
Returns
-------
renamed : Dataset
Dataset with renamed dimensions.
See Also
--------
Dataset.swap_dims
Dataset.rename
Dataset.rename_vars
DataArray.rename
"""
dims_dict = either_dict_or_kwargs(dims_dict, dims, "rename_dims")
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError(
"cannot rename %r because it is not a "
"dimension in this dataset" % k
)
if v in self.dims or v in self:
raise ValueError(
f"Cannot rename {k} to {v} because {v} already exists. "
"Try using swap_dims instead."
)
variables, coord_names, sizes, indexes = self._rename_all(
name_dict={}, dims_dict=dims_dict
)
return self._replace(variables, coord_names, dims=sizes, indexes=indexes)
def rename_vars(
self, name_dict: Mapping[Hashable, Hashable] = None, **names: Hashable
) -> "Dataset":
"""Returns a new object with renamed variables including coordinates
Parameters
----------
name_dict : dict-like, optional
Dictionary whose keys are current variable or coordinate names and
whose values are the desired names.
**names : optional
Keyword form of ``name_dict``.
One of name_dict or names must be provided.
Returns
-------
renamed : Dataset
Dataset with renamed variables including coordinates
See Also
--------
Dataset.swap_dims
Dataset.rename
Dataset.rename_dims
DataArray.rename
"""
name_dict = either_dict_or_kwargs(name_dict, names, "rename_vars")
for k in name_dict:
if k not in self:
raise ValueError(
"cannot rename %r because it is not a "
"variable or coordinate in this dataset" % k
)
variables, coord_names, dims, indexes = self._rename_all(
name_dict=name_dict, dims_dict={}
)
return self._replace(variables, coord_names, dims=dims, indexes=indexes)
def swap_dims(
self, dims_dict: Mapping[Hashable, Hashable] = None, **dims_kwargs
) -> "Dataset":
"""Returns a new object with swapped dimensions.
Parameters
----------
dims_dict : dict-like
Dictionary whose keys are current dimension names and whose values
are new names.
**dims_kwargs : {existing_dim: new_dim, ...}, optional
The keyword arguments form of ``dims_dict``.
One of dims_dict or dims_kwargs must be provided.
Returns
-------
swapped : Dataset
Dataset with swapped dimensions.
Examples
--------
>>> ds = xr.Dataset(
... data_vars={"a": ("x", [5, 7]), "b": ("x", [0.1, 2.4])},
... coords={"x": ["a", "b"], "y": ("x", [0, 1])},
... )
>>> ds
<xarray.Dataset>
Dimensions: (x: 2)
Coordinates:
* x (x) <U1 'a' 'b'
y (x) int64 0 1
Data variables:
a (x) int64 5 7
b (x) float64 0.1 2.4
>>> ds.swap_dims({"x": "y"})
<xarray.Dataset>
Dimensions: (y: 2)
Coordinates:
x (y) <U1 'a' 'b'
* y (y) int64 0 1
Data variables:
a (y) int64 5 7
b (y) float64 0.1 2.4
>>> ds.swap_dims({"x": "z"})
<xarray.Dataset>
Dimensions: (z: 2)
Coordinates:
x (z) <U1 'a' 'b'
y (z) int64 0 1
Dimensions without coordinates: z
Data variables:
a (z) int64 5 7
b (z) float64 0.1 2.4
See Also
--------
Dataset.rename
DataArray.swap_dims
"""
# TODO: deprecate this method in favor of a (less confusing)
# rename_dims() method that only renames dimensions.
dims_dict = either_dict_or_kwargs(dims_dict, dims_kwargs, "swap_dims")
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError(
"cannot swap from dimension %r because it is "
"not an existing dimension" % k
)
if v in self.variables and self.variables[v].dims != (k,):
raise ValueError(
"replacement dimension %r is not a 1D "
"variable along the old dimension %r" % (v, k)
)
result_dims = {dims_dict.get(dim, dim) for dim in self.dims}
coord_names = self._coord_names.copy()
coord_names.update({dim for dim in dims_dict.values() if dim in self.variables})
variables: Dict[Hashable, Variable] = {}
indexes: Dict[Hashable, pd.Index] = {}
for k, v in self.variables.items():
dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
if k in result_dims:
var = v.to_index_variable()
if k in self.indexes:
indexes[k] = self.indexes[k]
else:
new_index = var.to_index()
if new_index.nlevels == 1:
# make sure index name matches dimension name
new_index = new_index.rename(k)
indexes[k] = new_index
else:
var = v.to_base_variable()
var.dims = dims
variables[k] = var
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def expand_dims(
self,
dim: Union[None, Hashable, Sequence[Hashable], Mapping[Hashable, Any]] = None,
axis: Union[None, int, Sequence[int]] = None,
**dim_kwargs: Any,
) -> "Dataset":
"""Return a new object with an additional axis (or axes) inserted at
the corresponding position in the array shape. The new object is a
view into the underlying array, not a copy.
If dim is already a scalar coordinate, it will be promoted to a 1D
coordinate consisting of a single value.
Parameters
----------
dim : hashable, sequence of hashable, mapping, or None
Dimensions to include on the new variable. If provided as hashable
or sequence of hashable, then dimensions are inserted with length
1. If provided as a mapping, then the keys are the new dimensions
and the values are either integers (giving the length of the new
dimensions) or array-like (giving the coordinates of the new
dimensions).
axis : int, sequence of int, or None
Axis position(s) where new axis is to be inserted (position(s) on
the result array). If a list (or tuple) of integers is passed,
multiple axes are inserted. In this case, dim arguments should be
same length list. If axis=None is passed, all the axes will be
inserted to the start of the result array.
**dim_kwargs : int or sequence or ndarray
The keywords are arbitrary dimensions being inserted and the values
are either the lengths of the new dims (if int is given), or their
coordinates. Note, this is an alternative to passing a dict to the
dim kwarg and will only be used if dim is None.
Returns
-------
expanded : same type as caller
This object, but with an additional dimension(s).
"""
if dim is None:
pass
elif isinstance(dim, Mapping):
# We're later going to modify dim in place; don't tamper with
# the input
dim = dict(dim)
elif isinstance(dim, int):
raise TypeError(
"dim should be hashable or sequence of hashables or mapping"
)
elif isinstance(dim, str) or not isinstance(dim, Sequence):
dim = {dim: 1}
elif isinstance(dim, Sequence):
if len(dim) != len(set(dim)):
raise ValueError("dims should not contain duplicate values.")
dim = {d: 1 for d in dim}
dim = either_dict_or_kwargs(dim, dim_kwargs, "expand_dims")
assert isinstance(dim, MutableMapping)
if axis is None:
axis = list(range(len(dim)))
elif not isinstance(axis, Sequence):
axis = [axis]
if len(dim) != len(axis):
raise ValueError("lengths of dim and axis should be identical.")
for d in dim:
if d in self.dims:
raise ValueError(f"Dimension {d} already exists.")
if d in self._variables and not utils.is_scalar(self._variables[d]):
raise ValueError(
"{dim} already exists as coordinate or"
" variable name.".format(dim=d)
)
variables: Dict[Hashable, Variable] = {}
coord_names = self._coord_names.copy()
# If dim is a dict, then ensure that the values are either integers
# or iterables.
for k, v in dim.items():
if hasattr(v, "__iter__"):
# If the value for the new dimension is an iterable, then
# save the coordinates to the variables dict, and set the
# value within the dim dict to the length of the iterable
# for later use.
variables[k] = xr.IndexVariable((k,), v)
coord_names.add(k)
dim[k] = variables[k].size
elif isinstance(v, int):
pass # Do nothing if the dimensions value is just an int
else:
raise TypeError(
"The value of new dimension {k} must be "
"an iterable or an int".format(k=k)
)
for k, v in self._variables.items():
if k not in dim:
if k in coord_names: # Do not change coordinates
variables[k] = v
else:
result_ndim = len(v.dims) + len(axis)
for a in axis:
if a < -result_ndim or result_ndim - 1 < a:
raise IndexError(
f"Axis {a} of variable {k} is out of bounds of the "
f"expanded dimension size {result_ndim}"
)
axis_pos = [a if a >= 0 else result_ndim + a for a in axis]
if len(axis_pos) != len(set(axis_pos)):
raise ValueError("axis should not contain duplicate values")
# We need to sort them to make sure `axis` equals to the
# axis positions of the result array.
zip_axis_dim = sorted(zip(axis_pos, dim.items()))
all_dims = list(zip(v.dims, v.shape))
for d, c in zip_axis_dim:
all_dims.insert(d, c)
variables[k] = v.set_dims(dict(all_dims))
else:
# If dims includes a label of a non-dimension coordinate,
# it will be promoted to a 1D coordinate with a single value.
variables[k] = v.set_dims(k).to_index_variable()
new_dims = self._dims.copy()
new_dims.update(dim)
return self._replace_vars_and_dims(
variables, dims=new_dims, coord_names=coord_names
)
def set_index(
self,
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]] = None,
append: bool = False,
**indexes_kwargs: Union[Hashable, Sequence[Hashable]],
) -> "Dataset":
"""Set Dataset (multi-)indexes using one or more existing coordinates
or variables.
Parameters
----------
indexes : {dim: index, ...}
Mapping from names matching dimensions and values given
by (lists of) the names of existing coordinates or variables to set
as new (multi-)index.
append : bool, optional
If True, append the supplied index(es) to the existing index(es).
Otherwise replace the existing index(es) (default).
**indexes_kwargs : optional
The keyword arguments form of ``indexes``.
One of indexes or indexes_kwargs must be provided.
Returns
-------
obj : Dataset
Another dataset, with this dataset's data but replaced coordinates.
Examples
--------
>>> arr = xr.DataArray(
... data=np.ones((2, 3)),
... dims=["x", "y"],
... coords={"x": range(2), "y": range(3), "a": ("x", [3, 4])},
... )
>>> ds = xr.Dataset({"v": arr})
>>> ds
<xarray.Dataset>
Dimensions: (x: 2, y: 3)
Coordinates:
* x (x) int64 0 1
* y (y) int64 0 1 2
a (x) int64 3 4
Data variables:
v (x, y) float64 1.0 1.0 1.0 1.0 1.0 1.0
>>> ds.set_index(x="a")
<xarray.Dataset>
Dimensions: (x: 2, y: 3)
Coordinates:
* x (x) int64 3 4
* y (y) int64 0 1 2
Data variables:
v (x, y) float64 1.0 1.0 1.0 1.0 1.0 1.0
See Also
--------
Dataset.reset_index
Dataset.swap_dims
"""
indexes = either_dict_or_kwargs(indexes, indexes_kwargs, "set_index")
variables, coord_names = merge_indexes(
indexes, self._variables, self._coord_names, append=append
)
return self._replace_vars_and_dims(variables, coord_names=coord_names)
def reset_index(
self,
dims_or_levels: Union[Hashable, Sequence[Hashable]],
drop: bool = False,
) -> "Dataset":
"""Reset the specified index(es) or multi-index level(s).
Parameters
----------
dims_or_levels : str or list
Name(s) of the dimension(s) and/or multi-index level(s) that will
be reset.
drop : bool, optional
If True, remove the specified indexes and/or multi-index levels
instead of extracting them as new coordinates (default: False).
Returns
-------
obj : Dataset
Another dataset, with this dataset's data but replaced coordinates.
See Also
--------
Dataset.set_index
"""
variables, coord_names = split_indexes(
dims_or_levels,
self._variables,
self._coord_names,
cast(Mapping[Hashable, Hashable], self._level_coords),
drop=drop,
)
return self._replace_vars_and_dims(variables, coord_names=coord_names)
def reorder_levels(
self,
dim_order: Mapping[Hashable, Sequence[int]] = None,
**dim_order_kwargs: Sequence[int],
) -> "Dataset":
"""Rearrange index levels using input order.
Parameters
----------
dim_order : optional
Mapping from names matching dimensions and values given
by lists representing new level orders. Every given dimension
must have a multi-index.
**dim_order_kwargs : optional
The keyword arguments form of ``dim_order``.
One of dim_order or dim_order_kwargs must be provided.
Returns
-------
obj : Dataset
Another dataset, with this dataset's data but replaced
coordinates.
"""
dim_order = either_dict_or_kwargs(dim_order, dim_order_kwargs, "reorder_levels")
variables = self._variables.copy()
indexes = dict(self.indexes)
for dim, order in dim_order.items():
coord = self._variables[dim]
index = self.indexes[dim]
if not isinstance(index, pd.MultiIndex):
raise ValueError(f"coordinate {dim} has no MultiIndex")
new_index = index.reorder_levels(order)
variables[dim] = IndexVariable(coord.dims, new_index)
indexes[dim] = new_index
return self._replace(variables, indexes=indexes)
def _stack_once(self, dims, new_dim):
if ... in dims:
dims = list(infix_dims(dims, self.dims))
variables = {}
for name, var in self.variables.items():
if name not in dims:
if any(d in var.dims for d in dims):
add_dims = [d for d in dims if d not in var.dims]
vdims = list(var.dims) + add_dims
shape = [self.dims[d] for d in vdims]
exp_var = var.set_dims(vdims, shape)
stacked_var = exp_var.stack(**{new_dim: dims})
variables[name] = stacked_var
else:
variables[name] = var.copy(deep=False)
# consider dropping levels that are unused?
levels = [self.get_index(dim) for dim in dims]
idx = utils.multiindex_from_product_levels(levels, names=dims)
variables[new_dim] = IndexVariable(new_dim, idx)
coord_names = set(self._coord_names) - set(dims) | {new_dim}
indexes = {k: v for k, v in self.indexes.items() if k not in dims}
indexes[new_dim] = idx
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def stack(
self,
dimensions: Mapping[Hashable, Sequence[Hashable]] = None,
**dimensions_kwargs: Sequence[Hashable],
) -> "Dataset":
"""
Stack any number of existing dimensions into a single new dimension.
New dimensions will be added at the end, and the corresponding
coordinate variables will be combined into a MultiIndex.
Parameters
----------
dimensions : mapping of hashable to sequence of hashable
Mapping of the form `new_name=(dim1, dim2, ...)`. Names of new
dimensions, and the existing dimensions that they replace. An
ellipsis (`...`) will be replaced by all unlisted dimensions.
Passing a list containing an ellipsis (`stacked_dim=[...]`) will stack over
all dimensions.
**dimensions_kwargs
The keyword arguments form of ``dimensions``.
One of dimensions or dimensions_kwargs must be provided.
Returns
-------
stacked : Dataset
Dataset with stacked data.
See Also
--------
Dataset.unstack
"""
dimensions = either_dict_or_kwargs(dimensions, dimensions_kwargs, "stack")
result = self
for new_dim, dims in dimensions.items():
result = result._stack_once(dims, new_dim)
return result
def to_stacked_array(
self,
new_dim: Hashable,
sample_dims: Sequence[Hashable],
variable_dim: str = "variable",
name: Hashable = None,
) -> "DataArray":
"""Combine variables of differing dimensionality into a DataArray
without broadcasting.
This method is similar to Dataset.to_array but does not broadcast the
variables.
Parameters
----------
new_dim : hashable
Name of the new stacked coordinate
sample_dims : sequence of hashable
Dimensions that **will not** be stacked. Each array in the dataset
must share these dimensions. For machine learning applications,
these define the dimensions over which samples are drawn.
variable_dim : str, optional
Name of the level in the stacked coordinate which corresponds to
the variables.
name : str, optional
Name of the new data array.
Returns
-------
stacked : DataArray
DataArray with the specified dimensions and data variables
stacked together. The stacked coordinate is named ``new_dim``
and represented by a MultiIndex object with a level containing the
data variable names. The name of this level is controlled using
the ``variable_dim`` argument.
See Also
--------
Dataset.to_array
Dataset.stack
DataArray.to_unstacked_dataset
Examples
--------
>>> data = xr.Dataset(
... data_vars={
... "a": (("x", "y"), [[0, 1, 2], [3, 4, 5]]),
... "b": ("x", [6, 7]),
... },
... coords={"y": ["u", "v", "w"]},
... )
>>> data
<xarray.Dataset>
Dimensions: (x: 2, y: 3)
Coordinates:
* y (y) <U1 'u' 'v' 'w'
Dimensions without coordinates: x
Data variables:
a (x, y) int64 0 1 2 3 4 5
b (x) int64 6 7
>>> data.to_stacked_array("z", sample_dims=["x"])
<xarray.DataArray 'a' (x: 2, z: 4)>
array([[0, 1, 2, 6],
[3, 4, 5, 7]])
Coordinates:
* z (z) MultiIndex
- variable (z) object 'a' 'a' 'a' 'b'
- y (z) object 'u' 'v' 'w' nan
Dimensions without coordinates: x
"""
stacking_dims = tuple(dim for dim in self.dims if dim not in sample_dims)
for variable in self:
dims = self[variable].dims
dims_include_sample_dims = set(sample_dims) <= set(dims)
if not dims_include_sample_dims:
raise ValueError(
"All variables in the dataset must contain the "
"dimensions {}.".format(dims)
)
def ensure_stackable(val):
assign_coords = {variable_dim: val.name}
for dim in stacking_dims:
if dim not in val.dims:
assign_coords[dim] = None
expand_dims = set(stacking_dims).difference(set(val.dims))
expand_dims.add(variable_dim)
# must be list for .expand_dims
expand_dims = list(expand_dims)
return (
val.assign_coords(**assign_coords)
.expand_dims(expand_dims)
.stack({new_dim: (variable_dim,) + stacking_dims})
)
# concatenate the arrays
stackable_vars = [ensure_stackable(self[key]) for key in self.data_vars]
data_array = xr.concat(stackable_vars, dim=new_dim)
# coerce the levels of the MultiIndex to have the same type as the
# input dimensions. This code is messy, so it might be better to just
# input a dummy value for the singleton dimension.
idx = data_array.indexes[new_dim]
levels = [idx.levels[0]] + [
level.astype(self[level.name].dtype) for level in idx.levels[1:]
]
new_idx = idx.set_levels(levels)
data_array[new_dim] = IndexVariable(new_dim, new_idx)
if name is not None:
data_array.name = name
return data_array
def _unstack_once(self, dim: Hashable, fill_value) -> "Dataset":
index = self.get_index(dim)
index = remove_unused_levels_categories(index)
variables: Dict[Hashable, Variable] = {}
indexes = {k: v for k, v in self.indexes.items() if k != dim}
for name, var in self.variables.items():
if name != dim:
if dim in var.dims:
if isinstance(fill_value, Mapping):
fill_value_ = fill_value[name]
else:
fill_value_ = fill_value
variables[name] = var._unstack_once(
index=index, dim=dim, fill_value=fill_value_
)
else:
variables[name] = var
for name, lev in zip(index.names, index.levels):
variables[name] = IndexVariable(name, lev)
indexes[name] = lev
coord_names = set(self._coord_names) - {dim} | set(index.names)
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def _unstack_full_reindex(
self, dim: Hashable, fill_value, sparse: bool
) -> "Dataset":
index = self.get_index(dim)
index = remove_unused_levels_categories(index)
full_idx = pd.MultiIndex.from_product(index.levels, names=index.names)
# take a shortcut in case the MultiIndex was not modified.
if index.equals(full_idx):
obj = self
else:
obj = self._reindex(
{dim: full_idx}, copy=False, fill_value=fill_value, sparse=sparse
)
new_dim_names = index.names
new_dim_sizes = [lev.size for lev in index.levels]
variables: Dict[Hashable, Variable] = {}
indexes = {k: v for k, v in self.indexes.items() if k != dim}
for name, var in obj.variables.items():
if name != dim:
if dim in var.dims:
new_dims = dict(zip(new_dim_names, new_dim_sizes))
variables[name] = var.unstack({dim: new_dims})
else:
variables[name] = var
for name, lev in zip(new_dim_names, index.levels):
variables[name] = IndexVariable(name, lev)
indexes[name] = lev
coord_names = set(self._coord_names) - {dim} | set(new_dim_names)
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def unstack(
self,
dim: Union[Hashable, Iterable[Hashable]] = None,
fill_value: Any = dtypes.NA,
sparse: bool = False,
) -> "Dataset":
"""
Unstack existing dimensions corresponding to MultiIndexes into
multiple new dimensions.
New dimensions will be added at the end.
Parameters
----------
dim : hashable or iterable of hashable, optional
Dimension(s) over which to unstack. By default unstacks all
MultiIndexes.
fill_value : scalar or dict-like, default: nan
value to be filled. If a dict-like, maps variable names to
fill values. If not provided or if the dict-like does not
contain all variables, the dtype's NA value will be used.
sparse : bool, default: False
use sparse-array if True
Returns
-------
unstacked : Dataset
Dataset with unstacked data.
See Also
--------
Dataset.stack
"""
if dim is None:
dims = [
d for d in self.dims if isinstance(self.get_index(d), pd.MultiIndex)
]
else:
if isinstance(dim, str) or not isinstance(dim, Iterable):
dims = [dim]
else:
dims = list(dim)
missing_dims = [d for d in dims if d not in self.dims]
if missing_dims:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dims
)
non_multi_dims = [
d for d in dims if not isinstance(self.get_index(d), pd.MultiIndex)
]
if non_multi_dims:
raise ValueError(
"cannot unstack dimensions that do not "
"have a MultiIndex: %s" % non_multi_dims
)
result = self.copy(deep=False)
for dim in dims:
if (
# Dask arrays don't support assignment by index, which the fast unstack
# function requires.
# https://github.com/pydata/xarray/pull/4746#issuecomment-753282125
any(is_duck_dask_array(v.data) for v in self.variables.values())
# Sparse doesn't currently support (though we could special-case
# it)
# https://github.com/pydata/sparse/issues/422
or any(
isinstance(v.data, sparse_array_type)
for v in self.variables.values()
)
or sparse
# numpy full_like only added `shape` in 1.17
or LooseVersion(np.__version__) < LooseVersion("1.17")
# Until https://github.com/pydata/xarray/pull/4751 is resolved,
# we check explicitly whether it's a numpy array. Once that is
# resolved, explicitly exclude pint arrays.
# # pint doesn't implement `np.full_like` in a way that's
# # currently compatible.
# # https://github.com/pydata/xarray/pull/4746#issuecomment-753425173
# # or any(
# # isinstance(v.data, pint_array_type) for v in self.variables.values()
# # )
or any(
not isinstance(v.data, np.ndarray) for v in self.variables.values()
)
):
result = result._unstack_full_reindex(dim, fill_value, sparse)
else:
result = result._unstack_once(dim, fill_value)
return result
def update(self, other: "CoercibleMapping") -> "Dataset":
"""Update this dataset's variables with those from another dataset.
Just like :py:meth:`dict.update` this is a in-place operation.
Parameters
----------
other : Dataset or mapping
Variables with which to update this dataset. One of:
- Dataset
- mapping {var name: DataArray}
- mapping {var name: Variable}
- mapping {var name: (dimension name, array-like)}
- mapping {var name: (tuple of dimension names, array-like)}
Returns
-------
updated : Dataset
Updated dataset. Note that since the update is in-place this is the input
dataset.
It is deprecated since version 0.17 and scheduled to be removed in 0.19.
Raises
------
ValueError
If any dimensions would have inconsistent sizes in the updated
dataset.
See Also
--------
Dataset.assign
"""
merge_result = dataset_update_method(self, other)
return self._replace(inplace=True, **merge_result._asdict())
def merge(
self,
other: Union["CoercibleMapping", "DataArray"],
overwrite_vars: Union[Hashable, Iterable[Hashable]] = frozenset(),
compat: str = "no_conflicts",
join: str = "outer",
fill_value: Any = dtypes.NA,
combine_attrs: str = "override",
) -> "Dataset":
"""Merge the arrays of two datasets into a single dataset.
This method generally does not allow for overriding data, with the
exception of attributes, which are ignored on the second dataset.
Variables with the same name are checked for conflicts via the equals
or identical methods.
Parameters
----------
other : Dataset or mapping
Dataset or variables to merge with this dataset.
overwrite_vars : hashable or iterable of hashable, optional
If provided, update variables of these name(s) without checking for
conflicts in this dataset.
compat : {"broadcast_equals", "equals", "identical", \
"no_conflicts"}, optional
String indicating how to compare variables of the same name for
potential conflicts:
- 'broadcast_equals': all values must be equal when variables are
broadcast against each other to ensure common dimensions.
- 'equals': all values and dimensions must be the same.
- 'identical': all values, dimensions and attributes must be the
same.
- 'no_conflicts': only values which are not null in both datasets
must be equal. The returned dataset then contains the combination
of all non-null values.
join : {"outer", "inner", "left", "right", "exact"}, optional
Method for joining ``self`` and ``other`` along shared dimensions:
- 'outer': use the union of the indexes
- 'inner': use the intersection of the indexes
- 'left': use indexes from ``self``
- 'right': use indexes from ``other``
- 'exact': error instead of aligning non-equal indexes
fill_value : scalar or dict-like, optional
Value to use for newly missing values. If a dict-like, maps
variable names (including coordinates) to fill values.
combine_attrs : {"drop", "identical", "no_conflicts", "drop_conflicts", \
"override"}, default: "override"
String indicating how to combine attrs of the objects being merged:
- "drop": empty attrs on returned Dataset.
- "identical": all attrs must be the same on every object.
- "no_conflicts": attrs from all objects are combined, any that have
the same name must also have the same value.
- "drop_conflicts": attrs from all objects are combined, any that have
the same name but different values are dropped.
- "override": skip comparing and copy attrs from the first dataset to
the result.
Returns
-------
merged : Dataset
Merged dataset.
Raises
------
MergeError
If any variables conflict (see ``compat``).
"""
other = other.to_dataset() if isinstance(other, xr.DataArray) else other
merge_result = dataset_merge_method(
self,
other,
overwrite_vars=overwrite_vars,
compat=compat,
join=join,
fill_value=fill_value,
combine_attrs=combine_attrs,
)
return self._replace(**merge_result._asdict())
def _assert_all_in_dataset(
self, names: Iterable[Hashable], virtual_okay: bool = False
) -> None:
bad_names = set(names) - set(self._variables)
if virtual_okay:
bad_names -= self.virtual_variables
if bad_names:
raise ValueError(
"One or more of the specified variables "
"cannot be found in this dataset"
)
def drop_vars(
self, names: Union[Hashable, Iterable[Hashable]], *, errors: str = "raise"
) -> "Dataset":
"""Drop variables from this dataset.
Parameters
----------
names : hashable or iterable of hashable
Name(s) of variables to drop.
errors : {"raise", "ignore"}, optional
If 'raise' (default), raises a ValueError error if any of the variable
passed are not in the dataset. If 'ignore', any given names that are in the
dataset are dropped and no error is raised.
Returns
-------
dropped : Dataset
"""
# the Iterable check is required for mypy
if is_scalar(names) or not isinstance(names, Iterable):
names = {names}
else:
names = set(names)
if errors == "raise":
self._assert_all_in_dataset(names)
variables = {k: v for k, v in self._variables.items() if k not in names}
coord_names = {k for k in self._coord_names if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k not in names}
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def drop(self, labels=None, dim=None, *, errors="raise", **labels_kwargs):
"""Backward compatible method based on `drop_vars` and `drop_sel`
Using either `drop_vars` or `drop_sel` is encouraged
See Also
--------
Dataset.drop_vars
Dataset.drop_sel
"""
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
if is_dict_like(labels) and not isinstance(labels, dict):
warnings.warn(
"dropping coordinates using `drop` is be deprecated; use drop_vars.",
FutureWarning,
stacklevel=2,
)
return self.drop_vars(labels, errors=errors)
if labels_kwargs or isinstance(labels, dict):
if dim is not None:
raise ValueError("cannot specify dim and dict-like arguments.")
labels = either_dict_or_kwargs(labels, labels_kwargs, "drop")
if dim is None and (is_scalar(labels) or isinstance(labels, Iterable)):
warnings.warn(
"dropping variables using `drop` will be deprecated; using drop_vars is encouraged.",
PendingDeprecationWarning,
stacklevel=2,
)
return self.drop_vars(labels, errors=errors)
if dim is not None:
warnings.warn(
"dropping labels using list-like labels is deprecated; using "
"dict-like arguments with `drop_sel`, e.g. `ds.drop_sel(dim=[labels]).",
DeprecationWarning,
stacklevel=2,
)
return self.drop_sel({dim: labels}, errors=errors, **labels_kwargs)
warnings.warn(
"dropping labels using `drop` will be deprecated; using drop_sel is encouraged.",
PendingDeprecationWarning,
stacklevel=2,
)
return self.drop_sel(labels, errors=errors)
def drop_sel(self, labels=None, *, errors="raise", **labels_kwargs):
"""Drop index labels from this dataset.
Parameters
----------
labels : mapping of hashable to Any
Index labels to drop
errors : {"raise", "ignore"}, optional
If 'raise' (default), raises a ValueError error if
any of the index labels passed are not
in the dataset. If 'ignore', any given labels that are in the
dataset are dropped and no error is raised.
**labels_kwargs : {dim: label, ...}, optional
The keyword arguments form of ``dim`` and ``labels``
Returns
-------
dropped : Dataset
Examples
--------
>>> data = np.arange(6).reshape(2, 3)
>>> labels = ["a", "b", "c"]
>>> ds = xr.Dataset({"A": (["x", "y"], data), "y": labels})
>>> ds
<xarray.Dataset>
Dimensions: (x: 2, y: 3)
Coordinates:
* y (y) <U1 'a' 'b' 'c'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 0 1 2 3 4 5
>>> ds.drop_sel(y=["a", "c"])
<xarray.Dataset>
Dimensions: (x: 2, y: 1)
Coordinates:
* y (y) <U1 'b'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 1 4
>>> ds.drop_sel(y="b")
<xarray.Dataset>
Dimensions: (x: 2, y: 2)
Coordinates:
* y (y) <U1 'a' 'c'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 0 2 3 5
"""
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
labels = either_dict_or_kwargs(labels, labels_kwargs, "drop_sel")
ds = self
for dim, labels_for_dim in labels.items():
# Don't cast to set, as it would harm performance when labels
# is a large numpy array
if utils.is_scalar(labels_for_dim):
labels_for_dim = [labels_for_dim]
labels_for_dim = np.asarray(labels_for_dim)
try:
index = self.get_index(dim)
except KeyError:
raise ValueError("dimension %r does not have coordinate labels" % dim)
new_index = index.drop(labels_for_dim, errors=errors)
ds = ds.loc[{dim: new_index}]
return ds
def drop_isel(self, indexers=None, **indexers_kwargs):
"""Drop index positions from this Dataset.
Parameters
----------
indexers : mapping of hashable to Any
Index locations to drop
**indexers_kwargs : {dim: position, ...}, optional
The keyword arguments form of ``dim`` and ``positions``
Returns
-------
dropped : Dataset
Raises
------
IndexError
Examples
--------
>>> data = np.arange(6).reshape(2, 3)
>>> labels = ["a", "b", "c"]
>>> ds = xr.Dataset({"A": (["x", "y"], data), "y": labels})
>>> ds
<xarray.Dataset>
Dimensions: (x: 2, y: 3)
Coordinates:
* y (y) <U1 'a' 'b' 'c'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 0 1 2 3 4 5
>>> ds.drop_isel(y=[0, 2])
<xarray.Dataset>
Dimensions: (x: 2, y: 1)
Coordinates:
* y (y) <U1 'b'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 1 4
>>> ds.drop_isel(y=1)
<xarray.Dataset>
Dimensions: (x: 2, y: 2)
Coordinates:
* y (y) <U1 'a' 'c'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 0 2 3 5
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "drop_isel")
ds = self
dimension_index = {}
for dim, pos_for_dim in indexers.items():
# Don't cast to set, as it would harm performance when labels
# is a large numpy array
if utils.is_scalar(pos_for_dim):
pos_for_dim = [pos_for_dim]
pos_for_dim = np.asarray(pos_for_dim)
index = self.get_index(dim)
new_index = index.delete(pos_for_dim)
dimension_index[dim] = new_index
ds = ds.loc[dimension_index]
return ds
def drop_dims(
self, drop_dims: Union[Hashable, Iterable[Hashable]], *, errors: str = "raise"
) -> "Dataset":
"""Drop dimensions and associated variables from this dataset.
Parameters
----------
drop_dims : hashable or iterable of hashable
Dimension or dimensions to drop.
errors : {"raise", "ignore"}, optional
If 'raise' (default), raises a ValueError error if any of the
dimensions passed are not in the dataset. If 'ignore', any given
labels that are in the dataset are dropped and no error is raised.
Returns
-------
obj : Dataset
The dataset without the given dimensions (or any variables
containing those dimensions)
errors : {"raise", "ignore"}, optional
If 'raise' (default), raises a ValueError error if
any of the dimensions passed are not
in the dataset. If 'ignore', any given dimensions that are in the
dataset are dropped and no error is raised.
"""
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
if isinstance(drop_dims, str) or not isinstance(drop_dims, Iterable):
drop_dims = {drop_dims}
else:
drop_dims = set(drop_dims)
if errors == "raise":
missing_dims = drop_dims - set(self.dims)
if missing_dims:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dims
)
drop_vars = {k for k, v in self._variables.items() if set(v.dims) & drop_dims}
return self.drop_vars(drop_vars)
def transpose(self, *dims: Hashable) -> "Dataset":
"""Return a new Dataset object with all array dimensions transposed.
Although the order of dimensions on each array will change, the dataset
dimensions themselves will remain in fixed (sorted) order.
Parameters
----------
*dims : hashable, optional
By default, reverse the dimensions on each array. Otherwise,
reorder the dimensions to this order.
Returns
-------
transposed : Dataset
Each array in the dataset (including) coordinates will be
transposed to the given order.
Notes
-----
This operation returns a view of each array's data. It is
lazy for dask-backed DataArrays but not for numpy-backed DataArrays
-- the data will be fully loaded into memory.
See Also
--------
numpy.transpose
DataArray.transpose
"""
if dims:
if set(dims) ^ set(self.dims) and ... not in dims:
raise ValueError(
"arguments to transpose (%s) must be "
"permuted dataset dimensions (%s)" % (dims, tuple(self.dims))
)
ds = self.copy()
for name, var in self._variables.items():
var_dims = tuple(dim for dim in dims if dim in (var.dims + (...,)))
ds._variables[name] = var.transpose(*var_dims)
return ds
def dropna(
self,
dim: Hashable,
how: str = "any",
thresh: int = None,
subset: Iterable[Hashable] = None,
):
"""Returns a new dataset with dropped labels for missing values along
the provided dimension.
Parameters
----------
dim : hashable
Dimension along which to drop missing values. Dropping along
multiple dimensions simultaneously is not yet supported.
how : {"any", "all"}, default: "any"
* any : if any NA values are present, drop that label
* all : if all values are NA, drop that label
thresh : int, default: None
If supplied, require this many non-NA values.
subset : iterable of hashable, optional
Which variables to check for missing values. By default, all
variables in the dataset are checked.
Returns
-------
Dataset
"""
# TODO: consider supporting multiple dimensions? Or not, given that
# there are some ugly edge cases, e.g., pandas's dropna differs
# depending on the order of the supplied axes.
if dim not in self.dims:
raise ValueError("%s must be a single dataset dimension" % dim)
if subset is None:
subset = iter(self.data_vars)
count = np.zeros(self.dims[dim], dtype=np.int64)
size = np.int_(0) # for type checking
for k in subset:
array = self._variables[k]
if dim in array.dims:
dims = [d for d in array.dims if d != dim]
count += np.asarray(array.count(dims)) # type: ignore[attr-defined]
size += np.prod([self.dims[d] for d in dims])
if thresh is not None:
mask = count >= thresh
elif how == "any":
mask = count == size
elif how == "all":
mask = count > 0
elif how is not None:
raise ValueError("invalid how option: %s" % how)
else:
raise TypeError("must specify how or thresh")
return self.isel({dim: mask})
def fillna(self, value: Any) -> "Dataset":
"""Fill missing values in this object.
This operation follows the normal broadcasting and alignment rules that
xarray uses for binary arithmetic, except the result is aligned to this
object (``join='left'``) instead of aligned to the intersection of
index coordinates (``join='inner'``).
Parameters
----------
value : scalar, ndarray, DataArray, dict or Dataset
Used to fill all matching missing values in this dataset's data
variables. Scalars, ndarrays or DataArrays arguments are used to
fill all data with aligned coordinates (for DataArrays).
Dictionaries or datasets match data variables and then align
coordinates if necessary.
Returns
-------
Dataset
Examples
--------
>>> import numpy as np
>>> import xarray as xr
>>> ds = xr.Dataset(
... {
... "A": ("x", [np.nan, 2, np.nan, 0]),
... "B": ("x", [3, 4, np.nan, 1]),
... "C": ("x", [np.nan, np.nan, np.nan, 5]),
... "D": ("x", [np.nan, 3, np.nan, 4]),
... },
... coords={"x": [0, 1, 2, 3]},
... )
>>> ds
<xarray.Dataset>
Dimensions: (x: 4)
Coordinates:
* x (x) int64 0 1 2 3
Data variables:
A (x) float64 nan 2.0 nan 0.0
B (x) float64 3.0 4.0 nan 1.0
C (x) float64 nan nan nan 5.0
D (x) float64 nan 3.0 nan 4.0
Replace all `NaN` values with 0s.
>>> ds.fillna(0)
<xarray.Dataset>
Dimensions: (x: 4)
Coordinates:
* x (x) int64 0 1 2 3
Data variables:
A (x) float64 0.0 2.0 0.0 0.0
B (x) float64 3.0 4.0 0.0 1.0
C (x) float64 0.0 0.0 0.0 5.0
D (x) float64 0.0 3.0 0.0 4.0
Replace all `NaN` elements in column ‘A’, ‘B’, ‘C’, and ‘D’, with 0, 1, 2, and 3 respectively.
>>> values = {"A": 0, "B": 1, "C": 2, "D": 3}
>>> ds.fillna(value=values)
<xarray.Dataset>
Dimensions: (x: 4)
Coordinates:
* x (x) int64 0 1 2 3
Data variables:
A (x) float64 0.0 2.0 0.0 0.0
B (x) float64 3.0 4.0 1.0 1.0
C (x) float64 2.0 2.0 2.0 5.0
D (x) float64 3.0 3.0 3.0 4.0
"""
if utils.is_dict_like(value):
value_keys = getattr(value, "data_vars", value).keys()
if not set(value_keys) <= set(self.data_vars.keys()):
raise ValueError(
"all variables in the argument to `fillna` "
"must be contained in the original dataset"
)
out = ops.fillna(self, value)
return out
def interpolate_na(
self,
dim: Hashable = None,
method: str = "linear",
limit: int = None,
use_coordinate: Union[bool, Hashable] = True,
max_gap: Union[
int, float, str, pd.Timedelta, np.timedelta64, datetime.timedelta
] = None,
**kwargs: Any,
) -> "Dataset":
"""Fill in NaNs by interpolating according to different methods.
Parameters
----------
dim : str
Specifies the dimension along which to interpolate.
method : str, optional
String indicating which method to use for interpolation:
- 'linear': linear interpolation (Default). Additional keyword
arguments are passed to :py:func:`numpy.interp`
- 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'polynomial':
are passed to :py:func:`scipy.interpolate.interp1d`. If
``method='polynomial'``, the ``order`` keyword argument must also be
provided.
- 'barycentric', 'krog', 'pchip', 'spline', 'akima': use their
respective :py:class:`scipy.interpolate` classes.
use_coordinate : bool, str, default: True
Specifies which index to use as the x values in the interpolation
formulated as `y = f(x)`. If False, values are treated as if
eqaully-spaced along ``dim``. If True, the IndexVariable `dim` is
used. If ``use_coordinate`` is a string, it specifies the name of a
coordinate variariable to use as the index.
limit : int, default: None
Maximum number of consecutive NaNs to fill. Must be greater than 0
or None for no limit. This filling is done regardless of the size of
the gap in the data. To only interpolate over gaps less than a given length,
see ``max_gap``.
max_gap : int, float, str, pandas.Timedelta, numpy.timedelta64, datetime.timedelta, default: None
Maximum size of gap, a continuous sequence of NaNs, that will be filled.
Use None for no limit. When interpolating along a datetime64 dimension
and ``use_coordinate=True``, ``max_gap`` can be one of the following:
- a string that is valid input for pandas.to_timedelta
- a :py:class:`numpy.timedelta64` object
- a :py:class:`pandas.Timedelta` object
- a :py:class:`datetime.timedelta` object
Otherwise, ``max_gap`` must be an int or a float. Use of ``max_gap`` with unlabeled
dimensions has not been implemented yet. Gap length is defined as the difference
between coordinate values at the first data point after a gap and the last value
before a gap. For gaps at the beginning (end), gap length is defined as the difference
between coordinate values at the first (last) valid data point and the first (last) NaN.
For example, consider::
<xarray.DataArray (x: 9)>
array([nan, nan, nan, 1., nan, nan, 4., nan, nan])
Coordinates:
* x (x) int64 0 1 2 3 4 5 6 7 8
The gap lengths are 3-0 = 3; 6-3 = 3; and 8-6 = 2 respectively
kwargs : dict, optional
parameters passed verbatim to the underlying interpolation function
Returns
-------
interpolated: Dataset
Filled in Dataset.
See Also
--------
numpy.interp
scipy.interpolate
Examples
--------
>>> ds = xr.Dataset(
... {
... "A": ("x", [np.nan, 2, 3, np.nan, 0]),
... "B": ("x", [3, 4, np.nan, 1, 7]),
... "C": ("x", [np.nan, np.nan, np.nan, 5, 0]),
... "D": ("x", [np.nan, 3, np.nan, -1, 4]),
... },
... coords={"x": [0, 1, 2, 3, 4]},
... )
>>> ds
<xarray.Dataset>
Dimensions: (x: 5)
Coordinates:
* x (x) int64 0 1 2 3 4
Data variables:
A (x) float64 nan 2.0 3.0 nan 0.0
B (x) float64 3.0 4.0 nan 1.0 7.0
C (x) float64 nan nan nan 5.0 0.0
D (x) float64 nan 3.0 nan -1.0 4.0
>>> ds.interpolate_na(dim="x", method="linear")
<xarray.Dataset>
Dimensions: (x: 5)
Coordinates:
* x (x) int64 0 1 2 3 4
Data variables:
A (x) float64 nan 2.0 3.0 1.5 0.0
B (x) float64 3.0 4.0 2.5 1.0 7.0
C (x) float64 nan nan nan 5.0 0.0
D (x) float64 nan 3.0 1.0 -1.0 4.0
>>> ds.interpolate_na(dim="x", method="linear", fill_value="extrapolate")
<xarray.Dataset>
Dimensions: (x: 5)
Coordinates:
* x (x) int64 0 1 2 3 4
Data variables:
A (x) float64 1.0 2.0 3.0 1.5 0.0
B (x) float64 3.0 4.0 2.5 1.0 7.0
C (x) float64 20.0 15.0 10.0 5.0 0.0
D (x) float64 5.0 3.0 1.0 -1.0 4.0
"""
from .missing import _apply_over_vars_with_dim, interp_na
new = _apply_over_vars_with_dim(
interp_na,
self,
dim=dim,
method=method,
limit=limit,
use_coordinate=use_coordinate,
max_gap=max_gap,
**kwargs,
)
return new
def ffill(self, dim: Hashable, limit: int = None) -> "Dataset":
"""Fill NaN values by propogating values forward
*Requires bottleneck.*
Parameters
----------
dim : Hashable
Specifies the dimension along which to propagate values when
filling.
limit : int, default: None
The maximum number of consecutive NaN values to forward fill. In
other words, if there is a gap with more than this number of
consecutive NaNs, it will only be partially filled. Must be greater
than 0 or None for no limit.
Returns
-------
Dataset
"""
from .missing import _apply_over_vars_with_dim, ffill
new = _apply_over_vars_with_dim(ffill, self, dim=dim, limit=limit)
return new
def bfill(self, dim: Hashable, limit: int = None) -> "Dataset":
"""Fill NaN values by propogating values backward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default: None
The maximum number of consecutive NaN values to backward fill. In
other words, if there is a gap with more than this number of
consecutive NaNs, it will only be partially filled. Must be greater
than 0 or None for no limit.
Returns
-------
Dataset
"""
from .missing import _apply_over_vars_with_dim, bfill
new = _apply_over_vars_with_dim(bfill, self, dim=dim, limit=limit)
return new
def combine_first(self, other: "Dataset") -> "Dataset":
"""Combine two Datasets, default to data_vars of self.
The new coordinates follow the normal broadcasting and alignment rules
of ``join='outer'``. Vacant cells in the expanded coordinates are
filled with np.nan.
Parameters
----------
other : Dataset
Used to fill all matching missing values in this array.
Returns
-------
Dataset
"""
out = ops.fillna(self, other, join="outer", dataset_join="outer")
return out
def reduce(
self,
func: Callable,
dim: Union[Hashable, Iterable[Hashable]] = None,
keep_attrs: bool = None,
keepdims: bool = False,
numeric_only: bool = False,
**kwargs: Any,
) -> "Dataset":
"""Reduce this dataset by applying `func` along some dimension(s).
Parameters
----------
func : callable
Function which can be called in the form
`f(x, axis=axis, **kwargs)` to return the result of reducing an
np.ndarray over an integer valued axis.
dim : str or sequence of str, optional
Dimension(s) over which to apply `func`. By default `func` is
applied over all dimensions.
keep_attrs : bool, optional
If True, the dataset's attributes (`attrs`) will be copied from
the original object to the new one. If False (default), the new
object will be returned without attributes.
keepdims : bool, default: False
If True, the dimensions which are reduced are left in the result
as dimensions of size one. Coordinates that use these dimensions
are removed.
numeric_only : bool, optional
If True, only apply ``func`` to variables with a numeric dtype.
**kwargs : Any
Additional keyword arguments passed on to ``func``.
Returns
-------
reduced : Dataset
Dataset with this object's DataArrays replaced with new DataArrays
of summarized data and the indicated dimension(s) removed.
"""
if "axis" in kwargs:
raise ValueError(
"passing 'axis' to Dataset reduce methods is ambiguous."
" Please use 'dim' instead."
)
if dim is None or dim is ...:
dims = set(self.dims)
elif isinstance(dim, str) or not isinstance(dim, Iterable):
dims = {dim}
else:
dims = set(dim)
missing_dimensions = [d for d in dims if d not in self.dims]
if missing_dimensions:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dimensions
)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
variables: Dict[Hashable, Variable] = {}
for name, var in self._variables.items():
reduce_dims = [d for d in var.dims if d in dims]
if name in self.coords:
if not reduce_dims:
variables[name] = var
else:
if (
not numeric_only
or np.issubdtype(var.dtype, np.number)
or (var.dtype == np.bool_)
):
if len(reduce_dims) == 1:
# unpack dimensions for the benefit of functions
# like np.argmin which can't handle tuple arguments
(reduce_dims,) = reduce_dims
elif len(reduce_dims) == var.ndim:
# prefer to aggregate over axis=None rather than
# axis=(0, 1) if they will be equivalent, because
# the former is often more efficient
reduce_dims = None # type: ignore[assignment]
variables[name] = var.reduce(
func,
dim=reduce_dims,
keep_attrs=keep_attrs,
keepdims=keepdims,
**kwargs,
)
coord_names = {k for k in self.coords if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k in variables}
attrs = self.attrs if keep_attrs else None
return self._replace_with_new_dims(
variables, coord_names=coord_names, attrs=attrs, indexes=indexes
)
def map(
self,
func: Callable,
keep_attrs: bool = None,
args: Iterable[Any] = (),
**kwargs: Any,
) -> "Dataset":
"""Apply a function to each variable in this dataset
Parameters
----------
func : callable
Function which can be called in the form `func(x, *args, **kwargs)`
to transform each DataArray `x` in this dataset into another
DataArray.
keep_attrs : bool, optional
If True, the dataset's attributes (`attrs`) will be copied from
the original object to the new one. If False, the new object will
be returned without attributes.
args : tuple, optional
Positional arguments passed on to `func`.
**kwargs : Any
Keyword arguments passed on to `func`.
Returns
-------
applied : Dataset
Resulting dataset from applying ``func`` to each data variable.
Examples
--------
>>> da = xr.DataArray(np.random.randn(2, 3))
>>> ds = xr.Dataset({"foo": da, "bar": ("x", [-1, 2])})
>>> ds
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Dimensions without coordinates: dim_0, dim_1, x
Data variables:
foo (dim_0, dim_1) float64 1.764 0.4002 0.9787 2.241 1.868 -0.9773
bar (x) int64 -1 2
>>> ds.map(np.fabs)
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Dimensions without coordinates: dim_0, dim_1, x
Data variables:
foo (dim_0, dim_1) float64 1.764 0.4002 0.9787 2.241 1.868 0.9773
bar (x) float64 1.0 2.0
"""
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
variables = {
k: maybe_wrap_array(v, func(v, *args, **kwargs))
for k, v in self.data_vars.items()
}
if keep_attrs:
for k, v in variables.items():
v._copy_attrs_from(self.data_vars[k])
attrs = self.attrs if keep_attrs else None
return type(self)(variables, attrs=attrs)
def apply(
self,
func: Callable,
keep_attrs: bool = None,
args: Iterable[Any] = (),
**kwargs: Any,
) -> "Dataset":
"""
Backward compatible implementation of ``map``
See Also
--------
Dataset.map
"""
warnings.warn(
"Dataset.apply may be deprecated in the future. Using Dataset.map is encouraged",
PendingDeprecationWarning,
stacklevel=2,
)
return self.map(func, keep_attrs, args, **kwargs)
def assign(
self, variables: Mapping[Hashable, Any] = None, **variables_kwargs: Hashable
) -> "Dataset":
"""Assign new data variables to a Dataset, returning a new object
with all the original variables in addition to the new ones.
Parameters
----------
variables : mapping of hashable to Any
Mapping from variables names to the new values. If the new values
are callable, they are computed on the Dataset and assigned to new
data variables. If the values are not callable, (e.g. a DataArray,
scalar, or array), they are simply assigned.
**variables_kwargs
The keyword arguments form of ``variables``.
One of variables or variables_kwargs must be provided.
Returns
-------
ds : Dataset
A new Dataset with the new variables in addition to all the
existing variables.
Notes
-----
Since ``kwargs`` is a dictionary, the order of your arguments may not
be preserved, and so the order of the new variables is not well
defined. Assigning multiple variables within the same ``assign`` is
possible, but you cannot reference other variables created within the
same ``assign`` call.
See Also
--------
pandas.DataFrame.assign
Examples
--------
>>> x = xr.Dataset(
... {
... "temperature_c": (
... ("lat", "lon"),
... 20 * np.random.rand(4).reshape(2, 2),
... ),
... "precipitation": (("lat", "lon"), np.random.rand(4).reshape(2, 2)),
... },
... coords={"lat": [10, 20], "lon": [150, 160]},
... )
>>> x
<xarray.Dataset>
Dimensions: (lat: 2, lon: 2)
Coordinates:
* lat (lat) int64 10 20
* lon (lon) int64 150 160
Data variables:
temperature_c (lat, lon) float64 10.98 14.3 12.06 10.9
precipitation (lat, lon) float64 0.4237 0.6459 0.4376 0.8918
Where the value is a callable, evaluated on dataset:
>>> x.assign(temperature_f=lambda x: x.temperature_c * 9 / 5 + 32)
<xarray.Dataset>
Dimensions: (lat: 2, lon: 2)
Coordinates:
* lat (lat) int64 10 20
* lon (lon) int64 150 160
Data variables:
temperature_c (lat, lon) float64 10.98 14.3 12.06 10.9
precipitation (lat, lon) float64 0.4237 0.6459 0.4376 0.8918
temperature_f (lat, lon) float64 51.76 57.75 53.7 51.62
Alternatively, the same behavior can be achieved by directly referencing an existing dataarray:
>>> x.assign(temperature_f=x["temperature_c"] * 9 / 5 + 32)
<xarray.Dataset>
Dimensions: (lat: 2, lon: 2)
Coordinates:
* lat (lat) int64 10 20
* lon (lon) int64 150 160
Data variables:
temperature_c (lat, lon) float64 10.98 14.3 12.06 10.9
precipitation (lat, lon) float64 0.4237 0.6459 0.4376 0.8918
temperature_f (lat, lon) float64 51.76 57.75 53.7 51.62
"""
variables = either_dict_or_kwargs(variables, variables_kwargs, "assign")
data = self.copy()
# do all calculations first...
results = data._calc_assign_results(variables)
# ... and then assign
data.update(results)
return data
def to_array(self, dim="variable", name=None):
"""Convert this dataset into an xarray.DataArray
The data variables of this dataset will be broadcast against each other
and stacked along the first axis of the new array. All coordinates of
this dataset will remain coordinates.
Parameters
----------
dim : str, optional
Name of the new dimension.
name : str, optional
Name of the new data array.
Returns
-------
array : xarray.DataArray
"""
from .dataarray import DataArray
data_vars = [self.variables[k] for k in self.data_vars]
broadcast_vars = broadcast_variables(*data_vars)
data = duck_array_ops.stack([b.data for b in broadcast_vars], axis=0)
coords = dict(self.coords)
coords[dim] = list(self.data_vars)
indexes = propagate_indexes(self._indexes)
dims = (dim,) + broadcast_vars[0].dims
return DataArray(
data, coords, dims, attrs=self.attrs, name=name, indexes=indexes
)
def _normalize_dim_order(
self, dim_order: List[Hashable] = None
) -> Dict[Hashable, int]:
"""
Check the validity of the provided dimensions if any and return the mapping
between dimension name and their size.
Parameters
----------
dim_order
Dimension order to validate (default to the alphabetical order if None).
Returns
-------
result
Validated dimensions mapping.
"""
if dim_order is None:
dim_order = list(self.dims)
elif set(dim_order) != set(self.dims):
raise ValueError(
"dim_order {} does not match the set of dimensions of this "
"Dataset: {}".format(dim_order, list(self.dims))
)
ordered_dims = {k: self.dims[k] for k in dim_order}
return ordered_dims
def _to_dataframe(self, ordered_dims: Mapping[Hashable, int]):
columns = [k for k in self.variables if k not in self.dims]
data = [
self._variables[k].set_dims(ordered_dims).values.reshape(-1)
for k in columns
]
index = self.coords.to_index([*ordered_dims])
return pd.DataFrame(dict(zip(columns, data)), index=index)
def to_dataframe(self, dim_order: List[Hashable] = None) -> pd.DataFrame:
"""Convert this dataset into a pandas.DataFrame.
Non-index variables in this dataset form the columns of the
DataFrame. The DataFrame is indexed by the Cartesian product of
this dataset's indices.
Parameters
----------
dim_order
Hierarchical dimension order for the resulting dataframe. All
arrays are transposed to this order and then written out as flat
vectors in contiguous order, so the last dimension in this list
will be contiguous in the resulting DataFrame. This has a major
influence on which operations are efficient on the resulting
dataframe.
If provided, must include all dimensions of this dataset. By
default, dimensions are sorted alphabetically.
Returns
-------
result
Dataset as a pandas DataFrame.
"""
ordered_dims = self._normalize_dim_order(dim_order=dim_order)
return self._to_dataframe(ordered_dims=ordered_dims)
def _set_sparse_data_from_dataframe(
self, idx: pd.Index, arrays: List[Tuple[Hashable, np.ndarray]], dims: tuple
) -> None:
from sparse import COO
if isinstance(idx, pd.MultiIndex):
coords = np.stack([np.asarray(code) for code in idx.codes], axis=0)
is_sorted = idx.is_lexsorted()
shape = tuple(lev.size for lev in idx.levels)
else:
coords = np.arange(idx.size).reshape(1, -1)
is_sorted = True
shape = (idx.size,)
for name, values in arrays:
# In virtually all real use cases, the sparse array will now have
# missing values and needs a fill_value. For consistency, don't
# special case the rare exceptions (e.g., dtype=int without a
# MultiIndex).
dtype, fill_value = dtypes.maybe_promote(values.dtype)
values = np.asarray(values, dtype=dtype)
data = COO(
coords,
values,
shape,
has_duplicates=False,
sorted=is_sorted,
fill_value=fill_value,
)
self[name] = (dims, data)
def _set_numpy_data_from_dataframe(
self, idx: pd.Index, arrays: List[Tuple[Hashable, np.ndarray]], dims: tuple
) -> None:
if not isinstance(idx, pd.MultiIndex):
for name, values in arrays:
self[name] = (dims, values)
return
# NB: similar, more general logic, now exists in
# variable.unstack_once; we could consider combining them at some
# point.
shape = tuple(lev.size for lev in idx.levels)
indexer = tuple(idx.codes)
# We already verified that the MultiIndex has all unique values, so
# there are missing values if and only if the size of output arrays is
# larger that the index.
missing_values = np.prod(shape) > idx.shape[0]
for name, values in arrays:
# NumPy indexing is much faster than using DataFrame.reindex() to
# fill in missing values:
# https://stackoverflow.com/a/35049899/809705
if missing_values:
dtype, fill_value = dtypes.maybe_promote(values.dtype)
data = np.full(shape, fill_value, dtype)
else:
# If there are no missing values, keep the existing dtype
# instead of promoting to support NA, e.g., keep integer
# columns as integers.
# TODO: consider removing this special case, which doesn't
# exist for sparse=True.
data = np.zeros(shape, values.dtype)
data[indexer] = values
self[name] = (dims, data)
@classmethod
def from_dataframe(cls, dataframe: pd.DataFrame, sparse: bool = False) -> "Dataset":
"""Convert a pandas.DataFrame into an xarray.Dataset
Each column will be converted into an independent variable in the
Dataset. If the dataframe's index is a MultiIndex, it will be expanded
into a tensor product of one-dimensional indices (filling in missing
values with NaN). This method will produce a Dataset very similar to
that on which the 'to_dataframe' method was called, except with
possibly redundant dimensions (since all dataset variables will have
the same dimensionality)
Parameters
----------
dataframe : DataFrame
DataFrame from which to copy data and indices.
sparse : bool, default: False
If true, create a sparse arrays instead of dense numpy arrays. This
can potentially save a large amount of memory if the DataFrame has
a MultiIndex. Requires the sparse package (sparse.pydata.org).
Returns
-------
New Dataset.
See Also
--------
xarray.DataArray.from_series
pandas.DataFrame.to_xarray
"""
# TODO: Add an option to remove dimensions along which the variables
# are constant, to enable consistent serialization to/from a dataframe,
# even if some variables have different dimensionality.
if not dataframe.columns.is_unique:
raise ValueError("cannot convert DataFrame with non-unique columns")
idx = remove_unused_levels_categories(dataframe.index)
if isinstance(idx, pd.MultiIndex) and not idx.is_unique:
raise ValueError(
"cannot convert a DataFrame with a non-unique MultiIndex into xarray"
)
# Cast to a NumPy array first, in case the Series is a pandas Extension
# array (which doesn't have a valid NumPy dtype)
# TODO: allow users to control how this casting happens, e.g., by
# forwarding arguments to pandas.Series.to_numpy?
arrays = [(k, np.asarray(v)) for k, v in dataframe.items()]
obj = cls()
if isinstance(idx, pd.MultiIndex):
dims = tuple(
name if name is not None else "level_%i" % n
for n, name in enumerate(idx.names)
)
for dim, lev in zip(dims, idx.levels):
obj[dim] = (dim, lev)
else:
index_name = idx.name if idx.name is not None else "index"
dims = (index_name,)
obj[index_name] = (dims, idx)
if sparse:
obj._set_sparse_data_from_dataframe(idx, arrays, dims)
else:
obj._set_numpy_data_from_dataframe(idx, arrays, dims)
return obj
def to_dask_dataframe(self, dim_order=None, set_index=False):
"""
Convert this dataset into a dask.dataframe.DataFrame.
The dimensions, coordinates and data variables in this dataset form
the columns of the DataFrame.
Parameters
----------
dim_order : list, optional
Hierarchical dimension order for the resulting dataframe. All
arrays are transposed to this order and then written out as flat
vectors in contiguous order, so the last dimension in this list
will be contiguous in the resulting DataFrame. This has a major
influence on which operations are efficient on the resulting dask
dataframe.
If provided, must include all dimensions of this dataset. By
default, dimensions are sorted alphabetically.
set_index : bool, optional
If set_index=True, the dask DataFrame is indexed by this dataset's
coordinate. Since dask DataFrames do not support multi-indexes,
set_index only works if the dataset only contains one dimension.
Returns
-------
dask.dataframe.DataFrame
"""
import dask.array as da
import dask.dataframe as dd
ordered_dims = self._normalize_dim_order(dim_order=dim_order)
columns = list(ordered_dims)
columns.extend(k for k in self.coords if k not in self.dims)
columns.extend(self.data_vars)
series_list = []
for name in columns:
try:
var = self.variables[name]
except KeyError:
# dimension without a matching coordinate
size = self.dims[name]
data = da.arange(size, chunks=size, dtype=np.int64)
var = Variable((name,), data)
# IndexVariable objects have a dummy .chunk() method
if isinstance(var, IndexVariable):
var = var.to_base_variable()
dask_array = var.set_dims(ordered_dims).chunk(self.chunks).data
series = dd.from_array(dask_array.reshape(-1), columns=[name])
series_list.append(series)
df = dd.concat(series_list, axis=1)
if set_index:
dim_order = [*ordered_dims]
if len(dim_order) == 1:
(dim,) = dim_order
df = df.set_index(dim)
else:
# triggers an error about multi-indexes, even if only one
# dimension is passed
df = df.set_index(dim_order)
return df
def to_dict(self, data=True):
"""
Convert this dataset to a dictionary following xarray naming
conventions.
Converts all variables and attributes to native Python objects
Useful for converting to json. To avoid datetime incompatibility
use decode_times=False kwarg in xarrray.open_dataset.
Parameters
----------
data : bool, optional
Whether to include the actual data in the dictionary. When set to
False, returns just the schema.
See Also
--------
Dataset.from_dict
"""
d = {
"coords": {},
"attrs": decode_numpy_dict_values(self.attrs),
"dims": dict(self.dims),
"data_vars": {},
}
for k in self.coords:
d["coords"].update({k: self[k].variable.to_dict(data=data)})
for k in self.data_vars:
d["data_vars"].update({k: self[k].variable.to_dict(data=data)})
return d
@classmethod
def from_dict(cls, d):
"""
Convert a dictionary into an xarray.Dataset.
Input dict can take several forms:
.. code:: python
d = {
"t": {"dims": ("t"), "data": t},
"a": {"dims": ("t"), "data": x},
"b": {"dims": ("t"), "data": y},
}
d = {
"coords": {"t": {"dims": "t", "data": t, "attrs": {"units": "s"}}},
"attrs": {"title": "air temperature"},
"dims": "t",
"data_vars": {
"a": {"dims": "t", "data": x},
"b": {"dims": "t", "data": y},
},
}
where "t" is the name of the dimesion, "a" and "b" are names of data
variables and t, x, and y are lists, numpy.arrays or pandas objects.
Parameters
----------
d : dict-like
Mapping with a minimum structure of
``{"var_0": {"dims": [..], "data": [..]}, \
...}``
Returns
-------
obj : xarray.Dataset
See also
--------
Dataset.to_dict
DataArray.from_dict
"""
if not {"coords", "data_vars"}.issubset(set(d)):
variables = d.items()
else:
import itertools
variables = itertools.chain(
d.get("coords", {}).items(), d.get("data_vars", {}).items()
)
try:
variable_dict = {
k: (v["dims"], v["data"], v.get("attrs")) for k, v in variables
}
except KeyError as e:
raise ValueError(
"cannot convert dict without the key "
"'{dims_data}'".format(dims_data=str(e.args[0]))
)
obj = cls(variable_dict)
# what if coords aren't dims?
coords = set(d.get("coords", {})) - set(d.get("dims", {}))
obj = obj.set_coords(coords)
obj.attrs.update(d.get("attrs", {}))
return obj
@staticmethod
def _unary_op(f):
@functools.wraps(f)
def func(self, *args, **kwargs):
variables = {}
keep_attrs = kwargs.pop("keep_attrs", None)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
for k, v in self._variables.items():
if k in self._coord_names:
variables[k] = v
else:
variables[k] = f(v, *args, **kwargs)
if keep_attrs:
variables[k].attrs = v._attrs
attrs = self._attrs if keep_attrs else None
return self._replace_with_new_dims(variables, attrs=attrs)
return func
@staticmethod
def _binary_op(f, reflexive=False, join=None):
@functools.wraps(f)
def func(self, other):
from .dataarray import DataArray
if isinstance(other, groupby.GroupBy):
return NotImplemented
align_type = OPTIONS["arithmetic_join"] if join is None else join
if isinstance(other, (DataArray, Dataset)):
self, other = align(self, other, join=align_type, copy=False)
g = f if not reflexive else lambda x, y: f(y, x)
ds = self._calculate_binary_op(g, other, join=align_type)
return ds
return func
@staticmethod
def _inplace_binary_op(f):
@functools.wraps(f)
def func(self, other):
from .dataarray import DataArray
if isinstance(other, groupby.GroupBy):
raise TypeError(
"in-place operations between a Dataset and "
"a grouped object are not permitted"
)
# we don't actually modify arrays in-place with in-place Dataset
# arithmetic -- this lets us automatically align things
if isinstance(other, (DataArray, Dataset)):
other = other.reindex_like(self, copy=False)
g = ops.inplace_to_noninplace_op(f)
ds = self._calculate_binary_op(g, other, inplace=True)
self._replace_with_new_dims(
ds._variables,
ds._coord_names,
attrs=ds._attrs,
indexes=ds._indexes,
inplace=True,
)
return self
return func
def _calculate_binary_op(self, f, other, join="inner", inplace=False):
def apply_over_both(lhs_data_vars, rhs_data_vars, lhs_vars, rhs_vars):
if inplace and set(lhs_data_vars) != set(rhs_data_vars):
raise ValueError(
"datasets must have the same data variables "
"for in-place arithmetic operations: %s, %s"
% (list(lhs_data_vars), list(rhs_data_vars))
)
dest_vars = {}
for k in lhs_data_vars:
if k in rhs_data_vars:
dest_vars[k] = f(lhs_vars[k], rhs_vars[k])
elif join in ["left", "outer"]:
dest_vars[k] = f(lhs_vars[k], np.nan)
for k in rhs_data_vars:
if k not in dest_vars and join in ["right", "outer"]:
dest_vars[k] = f(rhs_vars[k], np.nan)
return dest_vars
if utils.is_dict_like(other) and not isinstance(other, Dataset):
# can't use our shortcut of doing the binary operation with
# Variable objects, so apply over our data vars instead.
new_data_vars = apply_over_both(
self.data_vars, other, self.data_vars, other
)
return Dataset(new_data_vars)
other_coords = getattr(other, "coords", None)
ds = self.coords.merge(other_coords)
if isinstance(other, Dataset):
new_vars = apply_over_both(
self.data_vars, other.data_vars, self.variables, other.variables
)
else:
other_variable = getattr(other, "variable", other)
new_vars = {k: f(self.variables[k], other_variable) for k in self.data_vars}
ds._variables.update(new_vars)
ds._dims = calculate_dimensions(ds._variables)
return ds
def _copy_attrs_from(self, other):
self.attrs = other.attrs
for v in other.variables:
if v in self.variables:
self.variables[v].attrs = other.variables[v].attrs
def diff(self, dim, n=1, label="upper"):
"""Calculate the n-th order discrete difference along given axis.
Parameters
----------
dim : str
Dimension over which to calculate the finite difference.
n : int, optional
The number of times values are differenced.
label : str, optional
The new coordinate in dimension ``dim`` will have the
values of either the minuend's or subtrahend's coordinate
for values 'upper' and 'lower', respectively. Other
values are not supported.
Returns
-------
difference : same type as caller
The n-th order finite difference of this object.
.. note::
`n` matches numpy's behavior and is different from pandas' first
argument named `periods`.
Examples
--------
>>> ds = xr.Dataset({"foo": ("x", [5, 5, 6, 6])})
>>> ds.diff("x")
<xarray.Dataset>
Dimensions: (x: 3)
Dimensions without coordinates: x
Data variables:
foo (x) int64 0 1 0
>>> ds.diff("x", 2)
<xarray.Dataset>
Dimensions: (x: 2)
Dimensions without coordinates: x
Data variables:
foo (x) int64 1 -1
See Also
--------
Dataset.differentiate
"""
if n == 0:
return self
if n < 0:
raise ValueError(f"order `n` must be non-negative but got {n}")
# prepare slices
kwargs_start = {dim: slice(None, -1)}
kwargs_end = {dim: slice(1, None)}
# prepare new coordinate
if label == "upper":
kwargs_new = kwargs_end
elif label == "lower":
kwargs_new = kwargs_start
else:
raise ValueError("The 'label' argument has to be either 'upper' or 'lower'")
variables = {}
for name, var in self.variables.items():
if dim in var.dims:
if name in self.data_vars:
variables[name] = var.isel(**kwargs_end) - var.isel(**kwargs_start)
else:
variables[name] = var.isel(**kwargs_new)
else:
variables[name] = var
indexes = dict(self.indexes)
if dim in indexes:
indexes[dim] = indexes[dim][kwargs_new[dim]]
difference = self._replace_with_new_dims(variables, indexes=indexes)
if n > 1:
return difference.diff(dim, n - 1)
else:
return difference
def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs):
"""Shift this dataset by an offset along one or more dimensions.
Only data variables are moved; coordinates stay in place. This is
consistent with the behavior of ``shift`` in pandas.
Parameters
----------
shifts : mapping of hashable to int
Integer offset to shift along each of the given dimensions.
Positive offsets shift to the right; negative offsets shift to the
left.
fill_value : scalar or dict-like, optional
Value to use for newly missing values. If a dict-like, maps
variable names (including coordinates) to fill values.
**shifts_kwargs
The keyword arguments form of ``shifts``.
One of shifts or shifts_kwargs must be provided.
Returns
-------
shifted : Dataset
Dataset with the same coordinates and attributes but shifted data
variables.
See Also
--------
roll
Examples
--------
>>> ds = xr.Dataset({"foo": ("x", list("abcde"))})
>>> ds.shift(x=2)
<xarray.Dataset>
Dimensions: (x: 5)
Dimensions without coordinates: x
Data variables:
foo (x) object nan nan 'a' 'b' 'c'
"""
shifts = either_dict_or_kwargs(shifts, shifts_kwargs, "shift")
invalid = [k for k in shifts if k not in self.dims]
if invalid:
raise ValueError("dimensions %r do not exist" % invalid)
variables = {}
for name, var in self.variables.items():
if name in self.data_vars:
fill_value_ = (
fill_value.get(name, dtypes.NA)
if isinstance(fill_value, dict)
else fill_value
)
var_shifts = {k: v for k, v in shifts.items() if k in var.dims}
variables[name] = var.shift(fill_value=fill_value_, shifts=var_shifts)
else:
variables[name] = var
return self._replace(variables)
def roll(self, shifts=None, roll_coords=None, **shifts_kwargs):
"""Roll this dataset by an offset along one or more dimensions.
Unlike shift, roll may rotate all variables, including coordinates
if specified. The direction of rotation is consistent with
:py:func:`numpy.roll`.
Parameters
----------
shifts : dict, optional
A dict with keys matching dimensions and values given
by integers to rotate each of the given dimensions. Positive
offsets roll to the right; negative offsets roll to the left.
roll_coords : bool
Indicates whether to roll the coordinates by the offset
The current default of roll_coords (None, equivalent to True) is
deprecated and will change to False in a future version.
Explicitly pass roll_coords to silence the warning.
**shifts_kwargs : {dim: offset, ...}, optional
The keyword arguments form of ``shifts``.
One of shifts or shifts_kwargs must be provided.
Returns
-------
rolled : Dataset
Dataset with the same coordinates and attributes but rolled
variables.
See Also
--------
shift
Examples
--------
>>> ds = xr.Dataset({"foo": ("x", list("abcde"))})
>>> ds.roll(x=2)
<xarray.Dataset>
Dimensions: (x: 5)
Dimensions without coordinates: x
Data variables:
foo (x) <U1 'd' 'e' 'a' 'b' 'c'
"""
shifts = either_dict_or_kwargs(shifts, shifts_kwargs, "roll")
invalid = [k for k in shifts if k not in self.dims]
if invalid:
raise ValueError("dimensions %r do not exist" % invalid)
if roll_coords is None:
warnings.warn(
"roll_coords will be set to False in the future."
" Explicitly set roll_coords to silence warning.",
FutureWarning,
stacklevel=2,
)
roll_coords = True
unrolled_vars = () if roll_coords else self.coords
variables = {}
for k, v in self.variables.items():
if k not in unrolled_vars:
variables[k] = v.roll(
**{k: s for k, s in shifts.items() if k in v.dims}
)
else:
variables[k] = v
if roll_coords:
indexes = {}
for k, v in self.indexes.items():
(dim,) = self.variables[k].dims
if dim in shifts:
indexes[k] = roll_index(v, shifts[dim])
else:
indexes[k] = v
else:
indexes = dict(self.indexes)
return self._replace(variables, indexes=indexes)
def sortby(self, variables, ascending=True):
"""
Sort object by labels or values (along an axis).
Sorts the dataset, either along specified dimensions,
or according to values of 1-D dataarrays that share dimension
with calling object.
If the input variables are dataarrays, then the dataarrays are aligned
(via left-join) to the calling object prior to sorting by cell values.
NaNs are sorted to the end, following Numpy convention.
If multiple sorts along the same dimension is
given, numpy's lexsort is performed along that dimension:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html
and the FIRST key in the sequence is used as the primary sort key,
followed by the 2nd key, etc.
Parameters
----------
variables : str, DataArray, or list of str or DataArray
1D DataArray objects or name(s) of 1D variable(s) in
coords/data_vars whose values are used to sort the dataset.
ascending : bool, optional
Whether to sort by ascending or descending order.
Returns
-------
sorted : Dataset
A new dataset where all the specified dims are sorted by dim
labels.
"""
from .dataarray import DataArray
if not isinstance(variables, list):
variables = [variables]
else:
variables = variables
variables = [v if isinstance(v, DataArray) else self[v] for v in variables]
aligned_vars = align(self, *variables, join="left")
aligned_self = aligned_vars[0]
aligned_other_vars = aligned_vars[1:]
vars_by_dim = defaultdict(list)
for data_array in aligned_other_vars:
if data_array.ndim != 1:
raise ValueError("Input DataArray is not 1-D.")
(key,) = data_array.dims
vars_by_dim[key].append(data_array)
indices = {}
for key, arrays in vars_by_dim.items():
order = np.lexsort(tuple(reversed(arrays)))
indices[key] = order if ascending else order[::-1]
return aligned_self.isel(**indices)
def quantile(
self,
q,
dim=None,
interpolation="linear",
numeric_only=False,
keep_attrs=None,
skipna=True,
):
"""Compute the qth quantile of the data along the specified dimension.
Returns the qth quantiles(s) of the array elements for each variable
in the Dataset.
Parameters
----------
q : float or array-like of float
Quantile to compute, which must be between 0 and 1 inclusive.
dim : str or sequence of str, optional
Dimension(s) over which to apply quantile.
interpolation : {"linear", "lower", "higher", "midpoint", "nearest"}, default: "linear"
This optional parameter specifies the interpolation method to
use when the desired quantile lies between two data points
``i < j``:
* linear: ``i + (j - i) * fraction``, where ``fraction`` is
the fractional part of the index surrounded by ``i`` and
``j``.
* lower: ``i``.
* higher: ``j``.
* nearest: ``i`` or ``j``, whichever is nearest.
* midpoint: ``(i + j) / 2``.
keep_attrs : bool, optional
If True, the dataset's attributes (`attrs`) will be copied from
the original object to the new one. If False (default), the new
object will be returned without attributes.
numeric_only : bool, optional
If True, only apply ``func`` to variables with a numeric dtype.
skipna : bool, optional
Whether to skip missing values when aggregating.
Returns
-------
quantiles : Dataset
If `q` is a single quantile, then the result is a scalar for each
variable in data_vars. If multiple percentiles are given, first
axis of the result corresponds to the quantile and a quantile
dimension is added to the return Dataset. The other dimensions are
the dimensions that remain after the reduction of the array.
See Also
--------
numpy.nanquantile, numpy.quantile, pandas.Series.quantile, DataArray.quantile
Examples
--------
>>> ds = xr.Dataset(
... {"a": (("x", "y"), [[0.7, 4.2, 9.4, 1.5], [6.5, 7.3, 2.6, 1.9]])},
... coords={"x": [7, 9], "y": [1, 1.5, 2, 2.5]},
... )
>>> ds.quantile(0) # or ds.quantile(0, dim=...)
<xarray.Dataset>
Dimensions: ()
Coordinates:
quantile float64 0.0
Data variables:
a float64 0.7
>>> ds.quantile(0, dim="x")
<xarray.Dataset>
Dimensions: (y: 4)
Coordinates:
* y (y) float64 1.0 1.5 2.0 2.5
quantile float64 0.0
Data variables:
a (y) float64 0.7 4.2 2.6 1.5
>>> ds.quantile([0, 0.5, 1])
<xarray.Dataset>
Dimensions: (quantile: 3)
Coordinates:
* quantile (quantile) float64 0.0 0.5 1.0
Data variables:
a (quantile) float64 0.7 3.4 9.4
>>> ds.quantile([0, 0.5, 1], dim="x")
<xarray.Dataset>
Dimensions: (quantile: 3, y: 4)
Coordinates:
* y (y) float64 1.0 1.5 2.0 2.5
* quantile (quantile) float64 0.0 0.5 1.0
Data variables:
a (quantile, y) float64 0.7 4.2 2.6 1.5 3.6 ... 1.7 6.5 7.3 9.4 1.9
"""
if isinstance(dim, str):
dims = {dim}
elif dim in [None, ...]:
dims = set(self.dims)
else:
dims = set(dim)
_assert_empty(
[d for d in dims if d not in self.dims],
"Dataset does not contain the dimensions: %s",
)
q = np.asarray(q, dtype=np.float64)
variables = {}
for name, var in self.variables.items():
reduce_dims = [d for d in var.dims if d in dims]
if reduce_dims or not var.dims:
if name not in self.coords:
if (
not numeric_only
or np.issubdtype(var.dtype, np.number)
or var.dtype == np.bool_
):
if len(reduce_dims) == var.ndim:
# prefer to aggregate over axis=None rather than
# axis=(0, 1) if they will be equivalent, because
# the former is often more efficient
reduce_dims = None
variables[name] = var.quantile(
q,
dim=reduce_dims,
interpolation=interpolation,
keep_attrs=keep_attrs,
skipna=skipna,
)
else:
variables[name] = var
# construct the new dataset
coord_names = {k for k in self.coords if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k in variables}
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
attrs = self.attrs if keep_attrs else None
new = self._replace_with_new_dims(
variables, coord_names=coord_names, attrs=attrs, indexes=indexes
)
return new.assign_coords(quantile=q)
def rank(self, dim, pct=False, keep_attrs=None):
"""Ranks the data.
Equal values are assigned a rank that is the average of the ranks that
would have been otherwise assigned to all of the values within
that set.
Ranks begin at 1, not 0. If pct is True, computes percentage ranks.
NaNs in the input array are returned as NaNs.
The `bottleneck` library is required.
Parameters
----------
dim : str
Dimension over which to compute rank.
pct : bool, optional
If True, compute percentage ranks, otherwise compute integer ranks.
keep_attrs : bool, optional
If True, the dataset's attributes (`attrs`) will be copied from
the original object to the new one. If False (default), the new
object will be returned without attributes.
Returns
-------
ranked : Dataset
Variables that do not depend on `dim` are dropped.
"""
if dim not in self.dims:
raise ValueError("Dataset does not contain the dimension: %s" % dim)
variables = {}
for name, var in self.variables.items():
if name in self.data_vars:
if dim in var.dims:
variables[name] = var.rank(dim, pct=pct)
else:
variables[name] = var
coord_names = set(self.coords)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
attrs = self.attrs if keep_attrs else None
return self._replace(variables, coord_names, attrs=attrs)
def differentiate(self, coord, edge_order=1, datetime_unit=None):
""" Differentiate with the second order accurate central
differences.
.. note::
This feature is limited to simple cartesian geometry, i.e. coord
must be one dimensional.
Parameters
----------
coord : str
The coordinate to be used to compute the gradient.
edge_order : {1, 2}, default: 1
N-th order accurate differences at the boundaries.
datetime_unit : None or {"Y", "M", "W", "D", "h", "m", "s", "ms", \
"us", "ns", "ps", "fs", "as"}, default: None
Unit to compute gradient. Only valid for datetime coordinate.
Returns
-------
differentiated: Dataset
See also
--------
numpy.gradient: corresponding numpy function
"""
from .variable import Variable
if coord not in self.variables and coord not in self.dims:
raise ValueError(f"Coordinate {coord} does not exist.")
coord_var = self[coord].variable
if coord_var.ndim != 1:
raise ValueError(
"Coordinate {} must be 1 dimensional but is {}"
" dimensional".format(coord, coord_var.ndim)
)
dim = coord_var.dims[0]
if _contains_datetime_like_objects(coord_var):
if coord_var.dtype.kind in "mM" and datetime_unit is None:
datetime_unit, _ = np.datetime_data(coord_var.dtype)
elif datetime_unit is None:
datetime_unit = "s" # Default to seconds for cftime objects
coord_var = coord_var._to_numeric(datetime_unit=datetime_unit)
variables = {}
for k, v in self.variables.items():
if k in self.data_vars and dim in v.dims and k not in self.coords:
if _contains_datetime_like_objects(v):
v = v._to_numeric(datetime_unit=datetime_unit)
grad = duck_array_ops.gradient(
v.data, coord_var, edge_order=edge_order, axis=v.get_axis_num(dim)
)
variables[k] = Variable(v.dims, grad)
else:
variables[k] = v
return self._replace(variables)
def integrate(
self, coord: Union[Hashable, Sequence[Hashable]], datetime_unit: str = None
) -> "Dataset":
"""Integrate along the given coordinate using the trapezoidal rule.
.. note::
This feature is limited to simple cartesian geometry, i.e. coord
must be one dimensional.
Parameters
----------
coord : hashable, or sequence of hashable
Coordinate(s) used for the integration.
datetime_unit : {'Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns', \
'ps', 'fs', 'as'}, optional
Specify the unit if datetime coordinate is used.
Returns
-------
integrated : Dataset
See also
--------
DataArray.integrate
numpy.trapz : corresponding numpy function
Examples
--------
>>> ds = xr.Dataset(
... data_vars={"a": ("x", [5, 5, 6, 6]), "b": ("x", [1, 2, 1, 0])},
... coords={"x": [0, 1, 2, 3], "y": ("x", [1, 7, 3, 5])},
... )
>>> ds
<xarray.Dataset>
Dimensions: (x: 4)
Coordinates:
* x (x) int64 0 1 2 3
y (x) int64 1 7 3 5
Data variables:
a (x) int64 5 5 6 6
b (x) int64 1 2 1 0
>>> ds.integrate("x")
<xarray.Dataset>
Dimensions: ()
Data variables:
a float64 16.5
b float64 3.5
>>> ds.integrate("y")
<xarray.Dataset>
Dimensions: ()
Data variables:
a float64 20.0
b float64 4.0
"""
if not isinstance(coord, (list, tuple)):
coord = (coord,)
result = self
for c in coord:
result = result._integrate_one(c, datetime_unit=datetime_unit)
return result
def _integrate_one(self, coord, datetime_unit=None):
from .variable import Variable
if coord not in self.variables and coord not in self.dims:
raise ValueError(f"Coordinate {coord} does not exist.")
coord_var = self[coord].variable
if coord_var.ndim != 1:
raise ValueError(
"Coordinate {} must be 1 dimensional but is {}"
" dimensional".format(coord, coord_var.ndim)
)
dim = coord_var.dims[0]
if _contains_datetime_like_objects(coord_var):
if coord_var.dtype.kind in "mM" and datetime_unit is None:
datetime_unit, _ = np.datetime_data(coord_var.dtype)
elif datetime_unit is None:
datetime_unit = "s" # Default to seconds for cftime objects
coord_var = coord_var._replace(
data=datetime_to_numeric(coord_var.data, datetime_unit=datetime_unit)
)
variables = {}
coord_names = set()
for k, v in self.variables.items():
if k in self.coords:
if dim not in v.dims:
variables[k] = v
coord_names.add(k)
else:
if k in self.data_vars and dim in v.dims:
if _contains_datetime_like_objects(v):
v = datetime_to_numeric(v, datetime_unit=datetime_unit)
integ = duck_array_ops.trapz(
v.data, coord_var.data, axis=v.get_axis_num(dim)
)
v_dims = list(v.dims)
v_dims.remove(dim)
variables[k] = Variable(v_dims, integ)
else:
variables[k] = v
indexes = {k: v for k, v in self.indexes.items() if k in variables}
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
@property
def real(self):
return self.map(lambda x: x.real, keep_attrs=True)
@property
def imag(self):
return self.map(lambda x: x.imag, keep_attrs=True)
plot = utils.UncachedAccessor(_Dataset_PlotMethods)
def filter_by_attrs(self, **kwargs):
"""Returns a ``Dataset`` with variables that match specific conditions.
Can pass in ``key=value`` or ``key=callable``. A Dataset is returned
containing only the variables for which all the filter tests pass.
These tests are either ``key=value`` for which the attribute ``key``
has the exact value ``value`` or the callable passed into
``key=callable`` returns True. The callable will be passed a single
value, either the value of the attribute ``key`` or ``None`` if the
DataArray does not have an attribute with the name ``key``.
Parameters
----------
**kwargs
key : str
Attribute name.
value : callable or obj
If value is a callable, it should return a boolean in the form
of bool = func(attr) where attr is da.attrs[key].
Otherwise, value will be compared to the each
DataArray's attrs[key].
Returns
-------
new : Dataset
New dataset with variables filtered by attribute.
Examples
--------
>>> # Create an example dataset:
>>> temp = 15 + 8 * np.random.randn(2, 2, 3)
>>> precip = 10 * np.random.rand(2, 2, 3)
>>> lon = [[-99.83, -99.32], [-99.79, -99.23]]
>>> lat = [[42.25, 42.21], [42.63, 42.59]]
>>> dims = ["x", "y", "time"]
>>> temp_attr = dict(standard_name="air_potential_temperature")
>>> precip_attr = dict(standard_name="convective_precipitation_flux")
>>> ds = xr.Dataset(
... {
... "temperature": (dims, temp, temp_attr),
... "precipitation": (dims, precip, precip_attr),
... },
... coords={
... "lon": (["x", "y"], lon),
... "lat": (["x", "y"], lat),
... "time": pd.date_range("2014-09-06", periods=3),
... "reference_time": pd.Timestamp("2014-09-05"),
... },
... )
>>> # Get variables matching a specific standard_name.
>>> ds.filter_by_attrs(standard_name="convective_precipitation_flux")
<xarray.Dataset>
Dimensions: (time: 3, x: 2, y: 2)
Coordinates:
lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
lat (x, y) float64 42.25 42.21 42.63 42.59
* time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
reference_time datetime64[ns] 2014-09-05
Dimensions without coordinates: x, y
Data variables:
precipitation (x, y, time) float64 5.68 9.256 0.7104 ... 7.992 4.615 7.805
>>> # Get all variables that have a standard_name attribute.
>>> standard_name = lambda v: v is not None
>>> ds.filter_by_attrs(standard_name=standard_name)
<xarray.Dataset>
Dimensions: (time: 3, x: 2, y: 2)
Coordinates:
lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
lat (x, y) float64 42.25 42.21 42.63 42.59
* time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
reference_time datetime64[ns] 2014-09-05
Dimensions without coordinates: x, y
Data variables:
temperature (x, y, time) float64 29.11 18.2 22.83 ... 18.28 16.15 26.63
precipitation (x, y, time) float64 5.68 9.256 0.7104 ... 7.992 4.615 7.805
"""
selection = []
for var_name, variable in self.variables.items():
has_value_flag = False
for attr_name, pattern in kwargs.items():
attr_value = variable.attrs.get(attr_name)
if (callable(pattern) and pattern(attr_value)) or attr_value == pattern:
has_value_flag = True
else:
has_value_flag = False
break
if has_value_flag is True:
selection.append(var_name)
return self[selection]
def unify_chunks(self) -> "Dataset":
"""Unify chunk size along all chunked dimensions of this Dataset.
Returns
-------
Dataset with consistent chunk sizes for all dask-array variables
See Also
--------
dask.array.core.unify_chunks
"""
try:
self.chunks
except ValueError: # "inconsistent chunks"
pass
else:
# No variables with dask backend, or all chunks are already aligned
return self.copy()
# import dask is placed after the quick exit test above to allow
# running this method if dask isn't installed and there are no chunks
import dask.array
ds = self.copy()
dims_pos_map = {dim: index for index, dim in enumerate(ds.dims)}
dask_array_names = []
dask_unify_args = []
for name, variable in ds.variables.items():
if isinstance(variable.data, dask.array.Array):
dims_tuple = [dims_pos_map[dim] for dim in variable.dims]
dask_array_names.append(name)
dask_unify_args.append(variable.data)
dask_unify_args.append(dims_tuple)
_, rechunked_arrays = dask.array.core.unify_chunks(*dask_unify_args)
for name, new_array in zip(dask_array_names, rechunked_arrays):
ds.variables[name]._data = new_array
return ds
def map_blocks(
self,
func: "Callable[..., T_DSorDA]",
args: Sequence[Any] = (),
kwargs: Mapping[str, Any] = None,
template: Union["DataArray", "Dataset"] = None,
) -> "T_DSorDA":
"""
Apply a function to each block of this Dataset.
.. warning::
This method is experimental and its signature may change.
Parameters
----------
func : callable
User-provided function that accepts a Dataset as its first
parameter. The function will receive a subset or 'block' of this Dataset (see below),
corresponding to one chunk along each chunked dimension. ``func`` will be
executed as ``func(subset_dataset, *subset_args, **kwargs)``.
This function must return either a single DataArray or a single Dataset.
This function cannot add a new chunked dimension.
args : sequence
Passed to func after unpacking and subsetting any xarray objects by blocks.
xarray objects in args must be aligned with obj, otherwise an error is raised.
kwargs : mapping
Passed verbatim to func after unpacking. xarray objects, if any, will not be
subset to blocks. Passing dask collections in kwargs is not allowed.
template : DataArray or Dataset, optional
xarray object representing the final result after compute is called. If not provided,
the function will be first run on mocked-up data, that looks like this object but
has sizes 0, to determine properties of the returned object such as dtype,
variable names, attributes, new dimensions and new indexes (if any).
``template`` must be provided if the function changes the size of existing dimensions.
When provided, ``attrs`` on variables in `template` are copied over to the result. Any
``attrs`` set by ``func`` will be ignored.
Returns
-------
A single DataArray or Dataset with dask backend, reassembled from the outputs of the
function.
Notes
-----
This function is designed for when ``func`` needs to manipulate a whole xarray object
subset to each block. Each block is loaded into memory. In the more common case where
``func`` can work on numpy arrays, it is recommended to use ``apply_ufunc``.
If none of the variables in this object is backed by dask arrays, calling this function is
equivalent to calling ``func(obj, *args, **kwargs)``.
See Also
--------
dask.array.map_blocks, xarray.apply_ufunc, xarray.Dataset.map_blocks
xarray.DataArray.map_blocks
Examples
--------
Calculate an anomaly from climatology using ``.groupby()``. Using
``xr.map_blocks()`` allows for parallel operations with knowledge of ``xarray``,
its indices, and its methods like ``.groupby()``.
>>> def calculate_anomaly(da, groupby_type="time.month"):
... gb = da.groupby(groupby_type)
... clim = gb.mean(dim="time")
... return gb - clim
...
>>> time = xr.cftime_range("1990-01", "1992-01", freq="M")
>>> month = xr.DataArray(time.month, coords={"time": time}, dims=["time"])
>>> np.random.seed(123)
>>> array = xr.DataArray(
... np.random.rand(len(time)),
... dims=["time"],
... coords={"time": time, "month": month},
... ).chunk()
>>> ds = xr.Dataset({"a": array})
>>> ds.map_blocks(calculate_anomaly, template=ds).compute()
<xarray.Dataset>
Dimensions: (time: 24)
Coordinates:
* time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00
month (time) int64 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12
Data variables:
a (time) float64 0.1289 0.1132 -0.0856 ... 0.2287 0.1906 -0.05901
Note that one must explicitly use ``args=[]`` and ``kwargs={}`` to pass arguments
to the function being applied in ``xr.map_blocks()``:
>>> ds.map_blocks(
... calculate_anomaly,
... kwargs={"groupby_type": "time.year"},
... template=ds,
... )
<xarray.Dataset>
Dimensions: (time: 24)
Coordinates:
* time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00
month (time) int64 dask.array<chunksize=(24,), meta=np.ndarray>
Data variables:
a (time) float64 dask.array<chunksize=(24,), meta=np.ndarray>
"""
from .parallel import map_blocks
return map_blocks(func, self, args, kwargs, template)
def polyfit(
self,
dim: Hashable,
deg: int,
skipna: bool = None,
rcond: float = None,
w: Union[Hashable, Any] = None,
full: bool = False,
cov: Union[bool, str] = False,
):
"""
Least squares polynomial fit.
This replicates the behaviour of `numpy.polyfit` but differs by skipping
invalid values when `skipna = True`.
Parameters
----------
dim : hashable
Coordinate along which to fit the polynomials.
deg : int
Degree of the fitting polynomial.
skipna : bool, optional
If True, removes all invalid values before fitting each 1D slices of the array.
Default is True if data is stored in a dask.array or if there is any
invalid values, False otherwise.
rcond : float, optional
Relative condition number to the fit.
w : hashable or Any, optional
Weights to apply to the y-coordinate of the sample points.
Can be an array-like object or the name of a coordinate in the dataset.
full : bool, optional
Whether to return the residuals, matrix rank and singular values in addition
to the coefficients.
cov : bool or str, optional
Whether to return to the covariance matrix in addition to the coefficients.
The matrix is not scaled if `cov='unscaled'`.
Returns
-------
polyfit_results : Dataset
A single dataset which contains (for each "var" in the input dataset):
[var]_polyfit_coefficients
The coefficients of the best fit for each variable in this dataset.
[var]_polyfit_residuals
The residuals of the least-square computation for each variable (only included if `full=True`)
When the matrix rank is deficient, np.nan is returned.
[dim]_matrix_rank
The effective rank of the scaled Vandermonde coefficient matrix (only included if `full=True`)
The rank is computed ignoring the NaN values that might be skipped.
[dim]_singular_values
The singular values of the scaled Vandermonde coefficient matrix (only included if `full=True`)
[var]_polyfit_covariance
The covariance matrix of the polynomial coefficient estimates (only included if `full=False` and `cov=True`)
Warns
-----
RankWarning
The rank of the coefficient matrix in the least-squares fit is deficient.
The warning is not raised with in-memory (not dask) data and `full=True`.
See Also
--------
numpy.polyfit
numpy.polyval
xarray.polyval
"""
variables = {}
skipna_da = skipna
x = get_clean_interp_index(self, dim, strict=False)
xname = "{}_".format(self[dim].name)
order = int(deg) + 1
lhs = np.vander(x, order)
if rcond is None:
rcond = (
x.shape[0] * np.core.finfo(x.dtype).eps # type: ignore[attr-defined]
)
# Weights:
if w is not None:
if isinstance(w, Hashable):
w = self.coords[w]
w = np.asarray(w)
if w.ndim != 1:
raise TypeError("Expected a 1-d array for weights.")
if w.shape[0] != lhs.shape[0]:
raise TypeError("Expected w and {} to have the same length".format(dim))
lhs *= w[:, np.newaxis]
# Scaling
scale = np.sqrt((lhs * lhs).sum(axis=0))
lhs /= scale
degree_dim = utils.get_temp_dimname(self.dims, "degree")
rank = np.linalg.matrix_rank(lhs)
if full:
rank = xr.DataArray(rank, name=xname + "matrix_rank")
variables[rank.name] = rank
sing = np.linalg.svd(lhs, compute_uv=False)
sing = xr.DataArray(
sing,
dims=(degree_dim,),
coords={degree_dim: np.arange(rank - 1, -1, -1)},
name=xname + "singular_values",
)
variables[sing.name] = sing
for name, da in self.data_vars.items():
if dim not in da.dims:
continue
if is_duck_dask_array(da.data) and (
rank != order or full or skipna is None
):
# Current algorithm with dask and skipna=False neither supports
# deficient ranks nor does it output the "full" info (issue dask/dask#6516)
skipna_da = True
elif skipna is None:
skipna_da = bool(np.any(da.isnull()))
dims_to_stack = [dimname for dimname in da.dims if dimname != dim]
stacked_coords: Dict[Hashable, DataArray] = {}
if dims_to_stack:
stacked_dim = utils.get_temp_dimname(dims_to_stack, "stacked")
rhs = da.transpose(dim, *dims_to_stack).stack(
{stacked_dim: dims_to_stack}
)
stacked_coords = {stacked_dim: rhs[stacked_dim]}
scale_da = scale[:, np.newaxis]
else:
rhs = da
scale_da = scale
if w is not None:
rhs *= w[:, np.newaxis]
with warnings.catch_warnings():
if full: # Copy np.polyfit behavior
warnings.simplefilter("ignore", np.RankWarning)
else: # Raise only once per variable
warnings.simplefilter("once", np.RankWarning)
coeffs, residuals = duck_array_ops.least_squares(
lhs, rhs.data, rcond=rcond, skipna=skipna_da
)
if isinstance(name, str):
name = "{}_".format(name)
else:
# Thus a ReprObject => polyfit was called on a DataArray
name = ""
coeffs = xr.DataArray(
coeffs / scale_da,
dims=[degree_dim] + list(stacked_coords.keys()),
coords={degree_dim: np.arange(order)[::-1], **stacked_coords},
name=name + "polyfit_coefficients",
)
if dims_to_stack:
coeffs = coeffs.unstack(stacked_dim)
variables[coeffs.name] = coeffs
if full or (cov is True):
residuals = xr.DataArray(
residuals if dims_to_stack else residuals.squeeze(),
dims=list(stacked_coords.keys()),
coords=stacked_coords,
name=name + "polyfit_residuals",
)
if dims_to_stack:
residuals = residuals.unstack(stacked_dim)
variables[residuals.name] = residuals
if cov:
Vbase = np.linalg.inv(np.dot(lhs.T, lhs))
Vbase /= np.outer(scale, scale)
if cov == "unscaled":
fac = 1
else:
if x.shape[0] <= order:
raise ValueError(
"The number of data points must exceed order to scale the covariance matrix."
)
fac = residuals / (x.shape[0] - order)
covariance = xr.DataArray(Vbase, dims=("cov_i", "cov_j")) * fac
variables[name + "polyfit_covariance"] = covariance
return Dataset(data_vars=variables, attrs=self.attrs.copy())
def pad(
self,
pad_width: Mapping[Hashable, Union[int, Tuple[int, int]]] = None,
mode: str = "constant",
stat_length: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
constant_values: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
end_values: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
reflect_type: str = None,
**pad_width_kwargs: Any,
) -> "Dataset":
"""Pad this dataset along one or more dimensions.
.. warning::
This function is experimental and its behaviour is likely to change
especially regarding padding of dimension coordinates (or IndexVariables).
When using one of the modes ("edge", "reflect", "symmetric", "wrap"),
coordinates will be padded with the same mode, otherwise coordinates
are padded using the "constant" mode with fill_value dtypes.NA.
Parameters
----------
pad_width : mapping of hashable to tuple of int
Mapping with the form of {dim: (pad_before, pad_after)}
describing the number of values padded along each dimension.
{dim: pad} is a shortcut for pad_before = pad_after = pad
mode : str, default: "constant"
One of the following string values (taken from numpy docs).
'constant' (default)
Pads with a constant value.
'edge'
Pads with the edge values of array.
'linear_ramp'
Pads with the linear ramp between end_value and the
array edge value.
'maximum'
Pads with the maximum value of all or part of the
vector along each axis.
'mean'
Pads with the mean value of all or part of the
vector along each axis.
'median'
Pads with the median value of all or part of the
vector along each axis.
'minimum'
Pads with the minimum value of all or part of the
vector along each axis.
'reflect'
Pads with the reflection of the vector mirrored on
the first and last values of the vector along each
axis.
'symmetric'
Pads with the reflection of the vector mirrored
along the edge of the array.
'wrap'
Pads with the wrap of the vector along the axis.
The first values are used to pad the end and the
end values are used to pad the beginning.
stat_length : int, tuple or mapping of hashable to tuple, default: None
Used in 'maximum', 'mean', 'median', and 'minimum'. Number of
values at edge of each axis used to calculate the statistic value.
{dim_1: (before_1, after_1), ... dim_N: (before_N, after_N)} unique
statistic lengths along each dimension.
((before, after),) yields same before and after statistic lengths
for each dimension.
(stat_length,) or int is a shortcut for before = after = statistic
length for all axes.
Default is ``None``, to use the entire axis.
constant_values : scalar, tuple or mapping of hashable to tuple, default: 0
Used in 'constant'. The values to set the padded values for each
axis.
``{dim_1: (before_1, after_1), ... dim_N: (before_N, after_N)}`` unique
pad constants along each dimension.
``((before, after),)`` yields same before and after constants for each
dimension.
``(constant,)`` or ``constant`` is a shortcut for ``before = after = constant`` for
all dimensions.
Default is 0.
end_values : scalar, tuple or mapping of hashable to tuple, default: 0
Used in 'linear_ramp'. The values used for the ending value of the
linear_ramp and that will form the edge of the padded array.
``{dim_1: (before_1, after_1), ... dim_N: (before_N, after_N)}`` unique
end values along each dimension.
``((before, after),)`` yields same before and after end values for each
axis.
``(constant,)`` or ``constant`` is a shortcut for ``before = after = constant`` for
all axes.
Default is 0.
reflect_type : {"even", "odd"}, optional
Used in "reflect", and "symmetric". The "even" style is the
default with an unaltered reflection around the edge value. For
the "odd" style, the extended part of the array is created by
subtracting the reflected values from two times the edge value.
**pad_width_kwargs
The keyword arguments form of ``pad_width``.
One of ``pad_width`` or ``pad_width_kwargs`` must be provided.
Returns
-------
padded : Dataset
Dataset with the padded coordinates and data.
See Also
--------
Dataset.shift, Dataset.roll, Dataset.bfill, Dataset.ffill, numpy.pad, dask.array.pad
Notes
-----
By default when ``mode="constant"`` and ``constant_values=None``, integer types will be
promoted to ``float`` and padded with ``np.nan``. To avoid type promotion
specify ``constant_values=np.nan``
Examples
--------
>>> ds = xr.Dataset({"foo": ("x", range(5))})
>>> ds.pad(x=(1, 2))
<xarray.Dataset>
Dimensions: (x: 8)
Dimensions without coordinates: x
Data variables:
foo (x) float64 nan 0.0 1.0 2.0 3.0 4.0 nan nan
"""
pad_width = either_dict_or_kwargs(pad_width, pad_width_kwargs, "pad")
if mode in ("edge", "reflect", "symmetric", "wrap"):
coord_pad_mode = mode
coord_pad_options = {
"stat_length": stat_length,
"constant_values": constant_values,
"end_values": end_values,
"reflect_type": reflect_type,
}
else:
coord_pad_mode = "constant"
coord_pad_options = {}
variables = {}
for name, var in self.variables.items():
var_pad_width = {k: v for k, v in pad_width.items() if k in var.dims}
if not var_pad_width:
variables[name] = var
elif name in self.data_vars:
variables[name] = var.pad(
pad_width=var_pad_width,
mode=mode,
stat_length=stat_length,
constant_values=constant_values,
end_values=end_values,
reflect_type=reflect_type,
)
else:
variables[name] = var.pad(
pad_width=var_pad_width,
mode=coord_pad_mode,
**coord_pad_options, # type: ignore[arg-type]
)
return self._replace_vars_and_dims(variables)
def idxmin(
self,
dim: Hashable = None,
skipna: bool = None,
fill_value: Any = dtypes.NA,
keep_attrs: bool = None,
) -> "Dataset":
"""Return the coordinate label of the minimum value along a dimension.
Returns a new `Dataset` named after the dimension with the values of
the coordinate labels along that dimension corresponding to minimum
values along that dimension.
In comparison to :py:meth:`~Dataset.argmin`, this returns the
coordinate label while :py:meth:`~Dataset.argmin` returns the index.
Parameters
----------
dim : str, optional
Dimension over which to apply `idxmin`. This is optional for 1D
variables, but required for variables with 2 or more dimensions.
skipna : bool or None, default: None
If True, skip missing values (as marked by NaN). By default, only
skips missing values for ``float``, ``complex``, and ``object``
dtypes; other dtypes either do not have a sentinel missing value
(``int``) or ``skipna=True`` has not been implemented
(``datetime64`` or ``timedelta64``).
fill_value : Any, default: NaN
Value to be filled in case all of the values along a dimension are
null. By default this is NaN. The fill value and result are
automatically converted to a compatible dtype if possible.
Ignored if ``skipna`` is False.
keep_attrs : bool, default: False
If True, the attributes (``attrs``) will be copied from the
original object to the new one. If False (default), the new object
will be returned without attributes.
Returns
-------
reduced : Dataset
New `Dataset` object with `idxmin` applied to its data and the
indicated dimension removed.
See Also
--------
DataArray.idxmin, Dataset.idxmax, Dataset.min, Dataset.argmin
Examples
--------
>>> array1 = xr.DataArray(
... [0, 2, 1, 0, -2], dims="x", coords={"x": ["a", "b", "c", "d", "e"]}
... )
>>> array2 = xr.DataArray(
... [
... [2.0, 1.0, 2.0, 0.0, -2.0],
... [-4.0, np.NaN, 2.0, np.NaN, -2.0],
... [np.NaN, np.NaN, 1.0, np.NaN, np.NaN],
... ],
... dims=["y", "x"],
... coords={"y": [-1, 0, 1], "x": ["a", "b", "c", "d", "e"]},
... )
>>> ds = xr.Dataset({"int": array1, "float": array2})
>>> ds.min(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int int64 -2
float (y) float64 -2.0 -4.0 1.0
>>> ds.argmin(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int int64 4
float (y) int64 4 0 2
>>> ds.idxmin(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int <U1 'e'
float (y) object 'e' 'a' 'c'
"""
return self.map(
methodcaller(
"idxmin",
dim=dim,
skipna=skipna,
fill_value=fill_value,
keep_attrs=keep_attrs,
)
)
def idxmax(
self,
dim: Hashable = None,
skipna: bool = None,
fill_value: Any = dtypes.NA,
keep_attrs: bool = None,
) -> "Dataset":
"""Return the coordinate label of the maximum value along a dimension.
Returns a new `Dataset` named after the dimension with the values of
the coordinate labels along that dimension corresponding to maximum
values along that dimension.
In comparison to :py:meth:`~Dataset.argmax`, this returns the
coordinate label while :py:meth:`~Dataset.argmax` returns the index.
Parameters
----------
dim : str, optional
Dimension over which to apply `idxmax`. This is optional for 1D
variables, but required for variables with 2 or more dimensions.
skipna : bool or None, default: None
If True, skip missing values (as marked by NaN). By default, only
skips missing values for ``float``, ``complex``, and ``object``
dtypes; other dtypes either do not have a sentinel missing value
(``int``) or ``skipna=True`` has not been implemented
(``datetime64`` or ``timedelta64``).
fill_value : Any, default: NaN
Value to be filled in case all of the values along a dimension are
null. By default this is NaN. The fill value and result are
automatically converted to a compatible dtype if possible.
Ignored if ``skipna`` is False.
keep_attrs : bool, default: False
If True, the attributes (``attrs``) will be copied from the
original object to the new one. If False (default), the new object
will be returned without attributes.
Returns
-------
reduced : Dataset
New `Dataset` object with `idxmax` applied to its data and the
indicated dimension removed.
See Also
--------
DataArray.idxmax, Dataset.idxmin, Dataset.max, Dataset.argmax
Examples
--------
>>> array1 = xr.DataArray(
... [0, 2, 1, 0, -2], dims="x", coords={"x": ["a", "b", "c", "d", "e"]}
... )
>>> array2 = xr.DataArray(
... [
... [2.0, 1.0, 2.0, 0.0, -2.0],
... [-4.0, np.NaN, 2.0, np.NaN, -2.0],
... [np.NaN, np.NaN, 1.0, np.NaN, np.NaN],
... ],
... dims=["y", "x"],
... coords={"y": [-1, 0, 1], "x": ["a", "b", "c", "d", "e"]},
... )
>>> ds = xr.Dataset({"int": array1, "float": array2})
>>> ds.max(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int int64 2
float (y) float64 2.0 2.0 1.0
>>> ds.argmax(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int int64 1
float (y) int64 0 2 2
>>> ds.idxmax(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int <U1 'b'
float (y) object 'a' 'c' 'c'
"""
return self.map(
methodcaller(
"idxmax",
dim=dim,
skipna=skipna,
fill_value=fill_value,
keep_attrs=keep_attrs,
)
)
def argmin(self, dim=None, **kwargs):
"""Indices of the minima of the member variables.
If there are multiple minima, the indices of the first one found will be
returned.
Parameters
----------
dim : str, optional
The dimension over which to find the minimum. By default, finds minimum over
all dimensions - for now returning an int for backward compatibility, but
this is deprecated, in future will be an error, since DataArray.argmin will
return a dict with indices for all dimensions, which does not make sense for
a Dataset.
keep_attrs : bool, optional
If True, the attributes (`attrs`) will be copied from the original
object to the new one. If False (default), the new object will be
returned without attributes.
skipna : bool, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or skipna=True has not been
implemented (object, datetime64 or timedelta64).
Returns
-------
result : Dataset
See Also
--------
DataArray.argmin
"""
if dim is None:
warnings.warn(
"Once the behaviour of DataArray.argmin() and Variable.argmin() without "
"dim changes to return a dict of indices of each dimension, for "
"consistency it will be an error to call Dataset.argmin() with no argument,"
"since we don't return a dict of Datasets.",
DeprecationWarning,
stacklevel=2,
)
if (
dim is None
or (not isinstance(dim, Sequence) and dim is not ...)
or isinstance(dim, str)
):
# Return int index if single dimension is passed, and is not part of a
# sequence
argmin_func = getattr(duck_array_ops, "argmin")
return self.reduce(argmin_func, dim=dim, **kwargs)
else:
raise ValueError(
"When dim is a sequence or ..., DataArray.argmin() returns a dict. "
"dicts cannot be contained in a Dataset, so cannot call "
"Dataset.argmin() with a sequence or ... for dim"
)
def argmax(self, dim=None, **kwargs):
"""Indices of the maxima of the member variables.
If there are multiple maxima, the indices of the first one found will be
returned.
Parameters
----------
dim : str, optional
The dimension over which to find the maximum. By default, finds maximum over
all dimensions - for now returning an int for backward compatibility, but
this is deprecated, in future will be an error, since DataArray.argmax will
return a dict with indices for all dimensions, which does not make sense for
a Dataset.
keep_attrs : bool, optional
If True, the attributes (`attrs`) will be copied from the original
object to the new one. If False (default), the new object will be
returned without attributes.
skipna : bool, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or skipna=True has not been
implemented (object, datetime64 or timedelta64).
Returns
-------
result : Dataset
See Also
--------
DataArray.argmax
"""
if dim is None:
warnings.warn(
"Once the behaviour of DataArray.argmin() and Variable.argmin() without "
"dim changes to return a dict of indices of each dimension, for "
"consistency it will be an error to call Dataset.argmin() with no argument,"
"since we don't return a dict of Datasets.",
DeprecationWarning,
stacklevel=2,
)
if (
dim is None
or (not isinstance(dim, Sequence) and dim is not ...)
or isinstance(dim, str)
):
# Return int index if single dimension is passed, and is not part of a
# sequence
argmax_func = getattr(duck_array_ops, "argmax")
return self.reduce(argmax_func, dim=dim, **kwargs)
else:
raise ValueError(
"When dim is a sequence or ..., DataArray.argmin() returns a dict. "
"dicts cannot be contained in a Dataset, so cannot call "
"Dataset.argmin() with a sequence or ... for dim"
)
def query(
self,
queries: Mapping[Hashable, Any] = None,
parser: str = "pandas",
engine: str = None,
missing_dims: str = "raise",
**queries_kwargs: Any,
) -> "Dataset":
"""Return a new dataset with each array indexed along the specified
dimension(s), where the indexers are given as strings containing
Python expressions to be evaluated against the data variables in the
dataset.
Parameters
----------
queries : dict, optional
A dict with keys matching dimensions and values given by strings
containing Python expressions to be evaluated against the data variables
in the dataset. The expressions will be evaluated using the pandas
eval() function, and can contain any valid Python expressions but cannot
contain any Python statements.
parser : {"pandas", "python"}, default: "pandas"
The parser to use to construct the syntax tree from the expression.
The default of 'pandas' parses code slightly different than standard
Python. Alternatively, you can parse an expression using the 'python'
parser to retain strict Python semantics.
engine: {"python", "numexpr", None}, default: None
The engine used to evaluate the expression. Supported engines are:
- None: tries to use numexpr, falls back to python
- "numexpr": evaluates expressions using numexpr
- "python": performs operations as if you had eval’d in top level python
missing_dims : {"raise", "warn", "ignore"}, default: "raise"
What to do if dimensions that should be selected from are not present in the
Dataset:
- "raise": raise an exception
- "warning": raise a warning, and ignore the missing dimensions
- "ignore": ignore the missing dimensions
**queries_kwargs : {dim: query, ...}, optional
The keyword arguments form of ``queries``.
One of queries or queries_kwargs must be provided.
Returns
-------
obj : Dataset
A new Dataset with the same contents as this dataset, except each
array and dimension is indexed by the results of the appropriate
queries.
See Also
--------
Dataset.isel
pandas.eval
"""
# allow queries to be given either as a dict or as kwargs
queries = either_dict_or_kwargs(queries, queries_kwargs, "query")
# check queries
for dim, expr in queries.items():
if not isinstance(expr, str):
msg = f"expr for dim {dim} must be a string to be evaluated, {type(expr)} given"
raise ValueError(msg)
# evaluate the queries to create the indexers
indexers = {
dim: pd.eval(expr, resolvers=[self], parser=parser, engine=engine)
for dim, expr in queries.items()
}
# apply the selection
return self.isel(indexers, missing_dims=missing_dims)
def curvefit(
self,
coords: Union[Union[str, "DataArray"], Iterable[Union[str, "DataArray"]]],
func: Callable[..., Any],
reduce_dims: Union[Hashable, Iterable[Hashable]] = None,
skipna: bool = True,
p0: Dict[str, Any] = None,
bounds: Dict[str, Any] = None,
param_names: Sequence[str] = None,
kwargs: Dict[str, Any] = None,
):
"""
Curve fitting optimization for arbitrary functions.
Wraps `scipy.optimize.curve_fit` with `apply_ufunc`.
Parameters
----------
coords : DataArray, str or sequence of DataArray, str
Independent coordinate(s) over which to perform the curve fitting. Must share
at least one dimension with the calling object. When fitting multi-dimensional
functions, supply `coords` as a sequence in the same order as arguments in
`func`. To fit along existing dimensions of the calling object, `coords` can
also be specified as a str or sequence of strs.
func : callable
User specified function in the form `f(x, *params)` which returns a numpy
array of length `len(x)`. `params` are the fittable parameters which are optimized
by scipy curve_fit. `x` can also be specified as a sequence containing multiple
coordinates, e.g. `f((x0, x1), *params)`.
reduce_dims : str or sequence of str
Additional dimension(s) over which to aggregate while fitting. For example,
calling `ds.curvefit(coords='time', reduce_dims=['lat', 'lon'], ...)` will
aggregate all lat and lon points and fit the specified function along the
time dimension.
skipna : bool, optional
Whether to skip missing values when fitting. Default is True.
p0 : dictionary, optional
Optional dictionary of parameter names to initial guesses passed to the
`curve_fit` `p0` arg. If none or only some parameters are passed, the rest will
be assigned initial values following the default scipy behavior.
bounds : dictionary, optional
Optional dictionary of parameter names to bounding values passed to the
`curve_fit` `bounds` arg. If none or only some parameters are passed, the rest
will be unbounded following the default scipy behavior.
param_names: seq, optional
Sequence of names for the fittable parameters of `func`. If not supplied,
this will be automatically determined by arguments of `func`. `param_names`
should be manually supplied when fitting a function that takes a variable
number of parameters.
kwargs : dictionary
Additional keyword arguments to passed to scipy curve_fit.
Returns
-------
curvefit_results : Dataset
A single dataset which contains:
[var]_curvefit_coefficients
The coefficients of the best fit.
[var]_curvefit_covariance
The covariance matrix of the coefficient estimates.
See also
--------
Dataset.polyfit
scipy.optimize.curve_fit
"""
from scipy.optimize import curve_fit
if p0 is None:
p0 = {}
if bounds is None:
bounds = {}
if kwargs is None:
kwargs = {}
if not reduce_dims:
reduce_dims_ = []
elif isinstance(reduce_dims, str) or not isinstance(reduce_dims, Iterable):
reduce_dims_ = [reduce_dims]
else:
reduce_dims_ = list(reduce_dims)
if (
isinstance(coords, str)
or isinstance(coords, xr.DataArray)
or not isinstance(coords, Iterable)
):
coords = [coords]
coords_ = [self[coord] if isinstance(coord, str) else coord for coord in coords]
# Determine whether any coords are dims on self
for coord in coords_:
reduce_dims_ += [c for c in self.dims if coord.equals(self[c])]
reduce_dims_ = list(set(reduce_dims_))
preserved_dims = list(set(self.dims) - set(reduce_dims_))
if not reduce_dims_:
raise ValueError(
"No arguments to `coords` were identified as a dimension on the calling "
"object, and no dims were supplied to `reduce_dims`. This would result "
"in fitting on scalar data."
)
# Broadcast all coords with each other
coords_ = xr.broadcast(*coords_)
coords_ = [
coord.broadcast_like(self, exclude=preserved_dims) for coord in coords_
]
params, func_args = _get_func_args(func, param_names)
param_defaults, bounds_defaults = _initialize_curvefit_params(
params, p0, bounds, func_args
)
n_params = len(params)
kwargs.setdefault("p0", [param_defaults[p] for p in params])
kwargs.setdefault(
"bounds",
[
[bounds_defaults[p][0] for p in params],
[bounds_defaults[p][1] for p in params],
],
)
def _wrapper(Y, *coords_, **kwargs):
# Wrap curve_fit with raveled coordinates and pointwise NaN handling
x = np.vstack([c.ravel() for c in coords_])
y = Y.ravel()
if skipna:
mask = np.all([np.any(~np.isnan(x), axis=0), ~np.isnan(y)], axis=0)
x = x[:, mask]
y = y[mask]
if not len(y):
popt = np.full([n_params], np.nan)
pcov = np.full([n_params, n_params], np.nan)
return popt, pcov
x = np.squeeze(x)
popt, pcov = curve_fit(func, x, y, **kwargs)
return popt, pcov
result = xr.Dataset()
for name, da in self.data_vars.items():
if name is xr.core.dataarray._THIS_ARRAY:
name = ""
else:
name = f"{str(name)}_"
popt, pcov = xr.apply_ufunc(
_wrapper,
da,
*coords_,
vectorize=True,
dask="parallelized",
input_core_dims=[reduce_dims_ for d in range(len(coords_) + 1)],
output_core_dims=[["param"], ["cov_i", "cov_j"]],
dask_gufunc_kwargs={
"output_sizes": {
"param": n_params,
"cov_i": n_params,
"cov_j": n_params,
},
},
output_dtypes=(np.float64, np.float64),
exclude_dims=set(reduce_dims_),
kwargs=kwargs,
)
result[name + "curvefit_coefficients"] = popt
result[name + "curvefit_covariance"] = pcov
result = result.assign_coords(
{"param": params, "cov_i": params, "cov_j": params}
)
result.attrs = self.attrs.copy()
return result
ops.inject_all_ops_and_reduce_methods(Dataset, array_only=False)
| 37.573694 | 124 | 0.56107 | import copy
import datetime
import functools
import inspect
import sys
import warnings
from collections import defaultdict
from distutils.version import LooseVersion
from html import escape
from numbers import Number
from operator import methodcaller
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
DefaultDict,
Dict,
Hashable,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy as np
import pandas as pd
import xarray as xr
from ..coding.cftimeindex import _parse_array_of_cftime_strings
from ..plot.dataset_plot import _Dataset_PlotMethods
from . import (
alignment,
dtypes,
duck_array_ops,
formatting,
formatting_html,
groupby,
ops,
resample,
rolling,
utils,
weighted,
)
from .alignment import _broadcast_helper, _get_broadcast_dims_map_common_coords, align
from .common import (
DataWithCoords,
ImplementsDatasetReduce,
_contains_datetime_like_objects,
)
from .coordinates import (
DatasetCoordinates,
assert_coordinate_consistent,
remap_label_indexers,
)
from .duck_array_ops import datetime_to_numeric
from .indexes import (
Indexes,
default_indexes,
isel_variable_and_index,
propagate_indexes,
remove_unused_levels_categories,
roll_index,
)
from .indexing import is_fancy_indexer
from .merge import (
dataset_merge_method,
dataset_update_method,
merge_coordinates_without_align,
merge_data_and_coords,
)
from .missing import get_clean_interp_index
from .options import OPTIONS, _get_keep_attrs
from .pycompat import is_duck_dask_array, sparse_array_type
from .utils import (
Default,
Frozen,
HybridMappingProxy,
SortedKeysDict,
_default,
decode_numpy_dict_values,
drop_dims_from_indexers,
either_dict_or_kwargs,
hashable,
infix_dims,
is_dict_like,
is_scalar,
maybe_wrap_array,
)
from .variable import (
IndexVariable,
Variable,
as_variable,
assert_unique_multiindex_level_names,
broadcast_variables,
)
if TYPE_CHECKING:
from ..backends import AbstractDataStore, ZarrStore
from .dataarray import DataArray
from .merge import CoercibleMapping
T_DSorDA = TypeVar("T_DSorDA", DataArray, "Dataset")
try:
from dask.delayed import Delayed
except ImportError:
Delayed = None
_DATETIMEINDEX_COMPONENTS = [
"year",
"month",
"day",
"hour",
"minute",
"second",
"microsecond",
"nanosecond",
"date",
"time",
"dayofyear",
"weekofyear",
"dayofweek",
"quarter",
]
def _get_virtual_variable(
variables, key: Hashable, level_vars: Mapping = None, dim_sizes: Mapping = None
) -> Tuple[Hashable, Hashable, Variable]:
if level_vars is None:
level_vars = {}
if dim_sizes is None:
dim_sizes = {}
if key in dim_sizes:
data = pd.Index(range(dim_sizes[key]), name=key)
variable = IndexVariable((key,), data)
return key, key, variable
if not isinstance(key, str):
raise KeyError(key)
split_key = key.split(".", 1)
var_name: Optional[str]
if len(split_key) == 2:
ref_name, var_name = split_key
elif len(split_key) == 1:
ref_name, var_name = key, None
else:
raise KeyError(key)
if ref_name in level_vars:
dim_var = variables[level_vars[ref_name]]
ref_var = dim_var.to_index_variable().get_level_variable(ref_name)
else:
ref_var = variables[ref_name]
if var_name is None:
virtual_var = ref_var
var_name = key
else:
if _contains_datetime_like_objects(ref_var):
ref_var = xr.DataArray(ref_var)
data = getattr(ref_var.dt, var_name).data
else:
data = getattr(ref_var, var_name).data
virtual_var = Variable(ref_var.dims, data)
return ref_name, var_name, virtual_var
def calculate_dimensions(variables: Mapping[Hashable, Variable]) -> Dict[Hashable, int]:
dims: Dict[Hashable, int] = {}
last_used = {}
scalar_vars = {k for k, v in variables.items() if not v.dims}
for k, var in variables.items():
for dim, size in zip(var.dims, var.shape):
if dim in scalar_vars:
raise ValueError(
"dimension %r already exists as a scalar variable" % dim
)
if dim not in dims:
dims[dim] = size
last_used[dim] = k
elif dims[dim] != size:
raise ValueError(
"conflicting sizes for dimension %r: "
"length %s on %r and length %s on %r"
% (dim, size, k, dims[dim], last_used[dim])
)
return dims
def merge_indexes(
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]],
variables: Mapping[Hashable, Variable],
coord_names: Set[Hashable],
append: bool = False,
) -> Tuple[Dict[Hashable, Variable], Set[Hashable]]:
vars_to_replace: Dict[Hashable, Variable] = {}
vars_to_remove: List[Hashable] = []
dims_to_replace: Dict[Hashable, Hashable] = {}
error_msg = "{} is not the name of an existing variable."
for dim, var_names in indexes.items():
if isinstance(var_names, str) or not isinstance(var_names, Sequence):
var_names = [var_names]
names: List[Hashable] = []
codes: List[List[int]] = []
levels: List[List[int]] = []
current_index_variable = variables.get(dim)
for n in var_names:
try:
var = variables[n]
except KeyError:
raise ValueError(error_msg.format(n))
if (
current_index_variable is not None
and var.dims != current_index_variable.dims
):
raise ValueError(
"dimension mismatch between %r %s and %r %s"
% (dim, current_index_variable.dims, n, var.dims)
)
if current_index_variable is not None and append:
current_index = current_index_variable.to_index()
if isinstance(current_index, pd.MultiIndex):
names.extend(current_index.names)
codes.extend(current_index.codes)
levels.extend(current_index.levels)
else:
names.append("%s_level_0" % dim)
cat = pd.Categorical(current_index.values, ordered=True)
codes.append(cat.codes)
levels.append(cat.categories)
if not len(names) and len(var_names) == 1:
idx = pd.Index(variables[var_names[0]].values)
else:
for n in var_names:
try:
var = variables[n]
except KeyError:
raise ValueError(error_msg.format(n))
names.append(n)
cat = pd.Categorical(var.values, ordered=True)
codes.append(cat.codes)
levels.append(cat.categories)
idx = pd.MultiIndex(levels, codes, names=names)
for n in names:
dims_to_replace[n] = dim
vars_to_replace[dim] = IndexVariable(dim, idx)
vars_to_remove.extend(var_names)
new_variables = {k: v for k, v in variables.items() if k not in vars_to_remove}
new_variables.update(vars_to_replace)
for k, v in new_variables.items():
if any(d in dims_to_replace for d in v.dims):
new_dims = [dims_to_replace.get(d, d) for d in v.dims]
new_variables[k] = v._replace(dims=new_dims)
new_coord_names = coord_names | set(vars_to_replace)
new_coord_names -= set(vars_to_remove)
return new_variables, new_coord_names
def split_indexes(
dims_or_levels: Union[Hashable, Sequence[Hashable]],
variables: Mapping[Hashable, Variable],
coord_names: Set[Hashable],
level_coords: Mapping[Hashable, Hashable],
drop: bool = False,
) -> Tuple[Dict[Hashable, Variable], Set[Hashable]]:
if isinstance(dims_or_levels, str) or not isinstance(dims_or_levels, Sequence):
dims_or_levels = [dims_or_levels]
dim_levels: DefaultDict[Any, List[Hashable]] = defaultdict(list)
dims = []
for k in dims_or_levels:
if k in level_coords:
dim_levels[level_coords[k]].append(k)
else:
dims.append(k)
vars_to_replace = {}
vars_to_create: Dict[Hashable, Variable] = {}
vars_to_remove = []
for d in dims:
index = variables[d].to_index()
if isinstance(index, pd.MultiIndex):
dim_levels[d] = index.names
else:
vars_to_remove.append(d)
if not drop:
vars_to_create[str(d) + "_"] = Variable(d, index, variables[d].attrs)
for d, levs in dim_levels.items():
index = variables[d].to_index()
if len(levs) == index.nlevels:
vars_to_remove.append(d)
else:
vars_to_replace[d] = IndexVariable(d, index.droplevel(levs))
if not drop:
for lev in levs:
idx = index.get_level_values(lev)
vars_to_create[idx.name] = Variable(d, idx, variables[d].attrs)
new_variables = dict(variables)
for v in set(vars_to_remove):
del new_variables[v]
new_variables.update(vars_to_replace)
new_variables.update(vars_to_create)
new_coord_names = (coord_names | set(vars_to_create)) - set(vars_to_remove)
return new_variables, new_coord_names
def _assert_empty(args: tuple, msg: str = "%s") -> None:
if args:
raise ValueError(msg % args)
def _check_chunks_compatibility(var, chunks, preferred_chunks):
for dim in var.dims:
if dim not in chunks or (dim not in preferred_chunks):
continue
preferred_chunks_dim = preferred_chunks.get(dim)
chunks_dim = chunks.get(dim)
if isinstance(chunks_dim, int):
chunks_dim = (chunks_dim,)
else:
chunks_dim = chunks_dim[:-1]
if any(s % preferred_chunks_dim for s in chunks_dim):
warnings.warn(
f"Specified Dask chunks {chunks[dim]} would separate "
f"on disks chunk shape {preferred_chunks[dim]} for dimension {dim}. "
"This could degrade performance. "
"Consider rechunking after loading instead.",
stacklevel=2,
)
def _get_chunk(var, chunks):
import dask.array as da
if isinstance(var, IndexVariable):
return {}
if isinstance(chunks, int) or (chunks == "auto"):
chunks = dict.fromkeys(var.dims, chunks)
preferred_chunks = var.encoding.get("preferred_chunks", {})
preferred_chunks_list = [
preferred_chunks.get(dim, shape) for dim, shape in zip(var.dims, var.shape)
]
chunks_list = [
chunks.get(dim, None) or preferred_chunks.get(dim, None) for dim in var.dims
]
output_chunks_list = da.core.normalize_chunks(
chunks_list,
shape=var.shape,
dtype=var.dtype,
previous_chunks=preferred_chunks_list,
)
output_chunks = dict(zip(var.dims, output_chunks_list))
_check_chunks_compatibility(var, output_chunks, preferred_chunks)
return output_chunks
def _maybe_chunk(
name,
var,
chunks,
token=None,
lock=None,
name_prefix="xarray-",
overwrite_encoded_chunks=False,
):
from dask.base import tokenize
if chunks is not None:
chunks = {dim: chunks[dim] for dim in var.dims if dim in chunks}
if var.ndim:
token2 = tokenize(name, token if token else var._data, chunks)
name2 = f"{name_prefix}{name}-{token2}"
var = var.chunk(chunks, name=name2, lock=lock)
if overwrite_encoded_chunks and var.chunks is not None:
var.encoding["chunks"] = tuple(x[0] for x in var.chunks)
return var
else:
return var
def as_dataset(obj: Any) -> "Dataset":
if hasattr(obj, "to_dataset"):
obj = obj.to_dataset()
if not isinstance(obj, Dataset):
obj = Dataset(obj)
return obj
def _get_func_args(func, param_names):
try:
func_args = inspect.signature(func).parameters
except ValueError:
func_args = {}
if not param_names:
raise ValueError(
"Unable to inspect `func` signature, and `param_names` was not provided."
)
if param_names:
params = param_names
else:
params = list(func_args)[1:]
if any(
[(p.kind in [p.VAR_POSITIONAL, p.VAR_KEYWORD]) for p in func_args.values()]
):
raise ValueError(
"`param_names` must be provided because `func` takes variable length arguments."
)
return params, func_args
def _initialize_curvefit_params(params, p0, bounds, func_args):
def _initialize_feasible(lb, ub):
lb_finite = np.isfinite(lb)
ub_finite = np.isfinite(ub)
p0 = np.nansum(
[
0.5 * (lb + ub) * int(lb_finite & ub_finite),
(lb + 1) * int(lb_finite & ~ub_finite),
(ub - 1) * int(~lb_finite & ub_finite),
]
)
return p0
param_defaults = {p: 1 for p in params}
bounds_defaults = {p: (-np.inf, np.inf) for p in params}
for p in params:
if p in func_args and func_args[p].default is not func_args[p].empty:
param_defaults[p] = func_args[p].default
if p in bounds:
bounds_defaults[p] = tuple(bounds[p])
if param_defaults[p] < bounds[p][0] or param_defaults[p] > bounds[p][1]:
param_defaults[p] = _initialize_feasible(bounds[p][0], bounds[p][1])
if p in p0:
param_defaults[p] = p0[p]
return param_defaults, bounds_defaults
class DataVariables(Mapping[Hashable, "DataArray"]):
__slots__ = ("_dataset",)
def __init__(self, dataset: "Dataset"):
self._dataset = dataset
def __iter__(self) -> Iterator[Hashable]:
return (
key
for key in self._dataset._variables
if key not in self._dataset._coord_names
)
def __len__(self) -> int:
return len(self._dataset._variables) - len(self._dataset._coord_names)
def __contains__(self, key: Hashable) -> bool:
return key in self._dataset._variables and key not in self._dataset._coord_names
def __getitem__(self, key: Hashable) -> "DataArray":
if key not in self._dataset._coord_names:
return cast("DataArray", self._dataset[key])
raise KeyError(key)
def __repr__(self) -> str:
return formatting.data_vars_repr(self)
@property
def variables(self) -> Mapping[Hashable, Variable]:
all_variables = self._dataset.variables
return Frozen({k: all_variables[k] for k in self})
def _ipython_key_completions_(self):
return [
key
for key in self._dataset._ipython_key_completions_()
if key not in self._dataset._coord_names
]
class _LocIndexer:
__slots__ = ("dataset",)
def __init__(self, dataset: "Dataset"):
self.dataset = dataset
def __getitem__(self, key: Mapping[Hashable, Any]) -> "Dataset":
if not utils.is_dict_like(key):
raise TypeError("can only lookup dictionaries from Dataset.loc")
return self.dataset.sel(key)
class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords):
_attrs: Optional[Dict[Hashable, Any]]
_cache: Dict[str, Any]
_coord_names: Set[Hashable]
_dims: Dict[Hashable, int]
_encoding: Optional[Dict[Hashable, Any]]
_close: Optional[Callable[[], None]]
_indexes: Optional[Dict[Hashable, pd.Index]]
_variables: Dict[Hashable, Variable]
__slots__ = (
"_attrs",
"_cache",
"_coord_names",
"_dims",
"_encoding",
"_close",
"_indexes",
"_variables",
"__weakref__",
)
_groupby_cls = groupby.DatasetGroupBy
_rolling_cls = rolling.DatasetRolling
_coarsen_cls = rolling.DatasetCoarsen
_resample_cls = resample.DatasetResample
_weighted_cls = weighted.DatasetWeighted
def __init__(
self,
data_vars: Mapping[Hashable, Any] = None,
coords: Mapping[Hashable, Any] = None,
attrs: Mapping[Hashable, Any] = None,
):
if data_vars is None:
data_vars = {}
if coords is None:
coords = {}
both_data_and_coords = set(data_vars) & set(coords)
if both_data_and_coords:
raise ValueError(
"variables %r are found in both data_vars and coords"
% both_data_and_coords
)
if isinstance(coords, Dataset):
coords = coords.variables
variables, coord_names, dims, indexes, _ = merge_data_and_coords(
data_vars, coords, compat="broadcast_equals"
)
self._attrs = dict(attrs) if attrs is not None else None
self._close = None
self._encoding = None
self._variables = variables
self._coord_names = coord_names
self._dims = dims
self._indexes = indexes
@classmethod
def load_store(cls, store, decoder=None) -> "Dataset":
variables, attributes = store.load()
if decoder:
variables, attributes = decoder(variables, attributes)
obj = cls(variables, attrs=attributes)
obj.set_close(store.close)
return obj
@property
def variables(self) -> Mapping[Hashable, Variable]:
return Frozen(self._variables)
@property
def attrs(self) -> Dict[Hashable, Any]:
if self._attrs is None:
self._attrs = {}
return self._attrs
@attrs.setter
def attrs(self, value: Mapping[Hashable, Any]) -> None:
self._attrs = dict(value)
@property
def encoding(self) -> Dict:
if self._encoding is None:
self._encoding = {}
return self._encoding
@encoding.setter
def encoding(self, value: Mapping) -> None:
self._encoding = dict(value)
@property
def dims(self) -> Mapping[Hashable, int]:
return Frozen(SortedKeysDict(self._dims))
@property
def sizes(self) -> Mapping[Hashable, int]:
return self.dims
def load(self, **kwargs) -> "Dataset":
lazy_data = {
k: v._data for k, v in self.variables.items() if is_duck_dask_array(v._data)
}
if lazy_data:
import dask.array as da
evaluated_data = da.compute(*lazy_data.values(), **kwargs)
for k, data in zip(lazy_data, evaluated_data):
self.variables[k].data = data
for k, v in self.variables.items():
if k not in lazy_data:
v.load()
return self
def __dask_tokenize__(self):
from dask.base import normalize_token
return normalize_token(
(type(self), self._variables, self._coord_names, self._attrs)
)
def __dask_graph__(self):
graphs = {k: v.__dask_graph__() for k, v in self.variables.items()}
graphs = {k: v for k, v in graphs.items() if v is not None}
if not graphs:
return None
else:
try:
from dask.highlevelgraph import HighLevelGraph
return HighLevelGraph.merge(*graphs.values())
except ImportError:
from dask import sharedict
return sharedict.merge(*graphs.values())
def __dask_keys__(self):
import dask
return [
v.__dask_keys__()
for v in self.variables.values()
if dask.is_dask_collection(v)
]
def __dask_layers__(self):
import dask
return sum(
[
v.__dask_layers__()
for v in self.variables.values()
if dask.is_dask_collection(v)
],
(),
)
@property
def __dask_optimize__(self):
import dask.array as da
return da.Array.__dask_optimize__
@property
def __dask_scheduler__(self):
import dask.array as da
return da.Array.__dask_scheduler__
def __dask_postcompute__(self):
return self._dask_postcompute, ()
def __dask_postpersist__(self):
return self._dask_postpersist, ()
def _dask_postcompute(self, results: "Iterable[Variable]") -> "Dataset":
import dask
variables = {}
results_iter = iter(results)
for k, v in self._variables.items():
if dask.is_dask_collection(v):
rebuild, args = v.__dask_postcompute__()
v = rebuild(next(results_iter), *args)
variables[k] = v
return Dataset._construct_direct(
variables,
self._coord_names,
self._dims,
self._attrs,
self._indexes,
self._encoding,
self._close,
)
def _dask_postpersist(
self, dsk: Mapping, *, rename: Mapping[str, str] = None
) -> "Dataset":
from dask import is_dask_collection
from dask.highlevelgraph import HighLevelGraph
from dask.optimization import cull
variables = {}
for k, v in self._variables.items():
if not is_dask_collection(v):
variables[k] = v
continue
if isinstance(dsk, HighLevelGraph):
# https://github.com/dask/dask/issues/7137
layers = v.__dask_layers__()
if rename:
layers = [rename.get(k, k) for k in layers]
dsk2 = dsk.cull_layers(layers)
elif rename: # pragma: nocover
# At the moment of writing, this is only for forward compatibility.
# replace_name_in_key requires dask >= 2021.3.
from dask.base import flatten, replace_name_in_key
keys = [
replace_name_in_key(k, rename) for k in flatten(v.__dask_keys__())
]
dsk2, _ = cull(dsk, keys)
else:
# __dask_postpersist__() was called by dask.optimize or dask.persist
dsk2, _ = cull(dsk, v.__dask_keys__())
rebuild, args = v.__dask_postpersist__()
# rename was added in dask 2021.3
kwargs = {"rename": rename} if rename else {}
variables[k] = rebuild(dsk2, *args, **kwargs)
return Dataset._construct_direct(
variables,
self._coord_names,
self._dims,
self._attrs,
self._indexes,
self._encoding,
self._close,
)
def compute(self, **kwargs) -> "Dataset":
new = self.copy(deep=False)
return new.load(**kwargs)
def _persist_inplace(self, **kwargs) -> "Dataset":
# access .data to coerce everything to numpy or dask arrays
lazy_data = {
k: v._data for k, v in self.variables.items() if is_duck_dask_array(v._data)
}
if lazy_data:
import dask
# evaluate all the dask arrays simultaneously
evaluated_data = dask.persist(*lazy_data.values(), **kwargs)
for k, data in zip(lazy_data, evaluated_data):
self.variables[k].data = data
return self
def persist(self, **kwargs) -> "Dataset":
new = self.copy(deep=False)
return new._persist_inplace(**kwargs)
@classmethod
def _construct_direct(
cls,
variables,
coord_names,
dims=None,
attrs=None,
indexes=None,
encoding=None,
close=None,
):
if dims is None:
dims = calculate_dimensions(variables)
obj = object.__new__(cls)
obj._variables = variables
obj._coord_names = coord_names
obj._dims = dims
obj._indexes = indexes
obj._attrs = attrs
obj._close = close
obj._encoding = encoding
return obj
def _replace(
self,
variables: Dict[Hashable, Variable] = None,
coord_names: Set[Hashable] = None,
dims: Dict[Any, int] = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
indexes: Union[Dict[Any, pd.Index], None, Default] = _default,
encoding: Union[dict, None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
if inplace:
if variables is not None:
self._variables = variables
if coord_names is not None:
self._coord_names = coord_names
if dims is not None:
self._dims = dims
if attrs is not _default:
self._attrs = attrs
if indexes is not _default:
self._indexes = indexes
if encoding is not _default:
self._encoding = encoding
obj = self
else:
if variables is None:
variables = self._variables.copy()
if coord_names is None:
coord_names = self._coord_names.copy()
if dims is None:
dims = self._dims.copy()
if attrs is _default:
attrs = copy.copy(self._attrs)
if indexes is _default:
indexes = copy.copy(self._indexes)
if encoding is _default:
encoding = copy.copy(self._encoding)
obj = self._construct_direct(
variables, coord_names, dims, attrs, indexes, encoding
)
return obj
def _replace_with_new_dims(
self,
variables: Dict[Hashable, Variable],
coord_names: set = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
indexes: Union[Dict[Hashable, pd.Index], None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
dims = calculate_dimensions(variables)
return self._replace(
variables, coord_names, dims, attrs, indexes, inplace=inplace
)
def _replace_vars_and_dims(
self,
variables: Dict[Hashable, Variable],
coord_names: set = None,
dims: Dict[Hashable, int] = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
if dims is None:
dims = calculate_dimensions(variables)
return self._replace(
variables, coord_names, dims, attrs, indexes=None, inplace=inplace
)
def _overwrite_indexes(self, indexes: Mapping[Any, pd.Index]) -> "Dataset":
if not indexes:
return self
variables = self._variables.copy()
new_indexes = dict(self.indexes)
for name, idx in indexes.items():
variables[name] = IndexVariable(name, idx)
new_indexes[name] = idx
obj = self._replace(variables, indexes=new_indexes)
# switch from dimension to level names, if necessary
dim_names: Dict[Hashable, str] = {}
for dim, idx in indexes.items():
if not isinstance(idx, pd.MultiIndex) and idx.name != dim:
dim_names[dim] = idx.name
if dim_names:
obj = obj.rename(dim_names)
return obj
def copy(self, deep: bool = False, data: Mapping = None) -> "Dataset":
if data is None:
variables = {k: v.copy(deep=deep) for k, v in self._variables.items()}
elif not utils.is_dict_like(data):
raise ValueError("Data must be dict-like")
else:
var_keys = set(self.data_vars.keys())
data_keys = set(data.keys())
keys_not_in_vars = data_keys - var_keys
if keys_not_in_vars:
raise ValueError(
"Data must only contain variables in original "
"dataset. Extra variables: {}".format(keys_not_in_vars)
)
keys_missing_from_data = var_keys - data_keys
if keys_missing_from_data:
raise ValueError(
"Data must contain all variables in original "
"dataset. Data is missing {}".format(keys_missing_from_data)
)
variables = {
k: v.copy(deep=deep, data=data.get(k))
for k, v in self._variables.items()
}
attrs = copy.deepcopy(self._attrs) if deep else copy.copy(self._attrs)
return self._replace(variables, attrs=attrs)
@property
def _level_coords(self) -> Dict[str, Hashable]:
level_coords: Dict[str, Hashable] = {}
for name, index in self.indexes.items():
if isinstance(index, pd.MultiIndex):
level_names = index.names
(dim,) = self.variables[name].dims
level_coords.update({lname: dim for lname in level_names})
return level_coords
def _copy_listed(self, names: Iterable[Hashable]) -> "Dataset":
variables: Dict[Hashable, Variable] = {}
coord_names = set()
indexes: Dict[Hashable, pd.Index] = {}
for name in names:
try:
variables[name] = self._variables[name]
except KeyError:
ref_name, var_name, var = _get_virtual_variable(
self._variables, name, self._level_coords, self.dims
)
variables[var_name] = var
if ref_name in self._coord_names or ref_name in self.dims:
coord_names.add(var_name)
if (var_name,) == var.dims:
indexes[var_name] = var.to_index()
needed_dims: Set[Hashable] = set()
for v in variables.values():
needed_dims.update(v.dims)
dims = {k: self.dims[k] for k in needed_dims}
# preserves ordering of coordinates
for k in self._variables:
if k not in self._coord_names:
continue
if set(self.variables[k].dims) <= needed_dims:
variables[k] = self._variables[k]
coord_names.add(k)
if k in self.indexes:
indexes[k] = self.indexes[k]
return self._replace(variables, coord_names, dims, indexes=indexes)
def _construct_dataarray(self, name: Hashable) -> "DataArray":
from .dataarray import DataArray
try:
variable = self._variables[name]
except KeyError:
_, name, variable = _get_virtual_variable(
self._variables, name, self._level_coords, self.dims
)
needed_dims = set(variable.dims)
coords: Dict[Hashable, Variable] = {}
# preserve ordering
for k in self._variables:
if k in self._coord_names and set(self.variables[k].dims) <= needed_dims:
coords[k] = self.variables[k]
if self._indexes is None:
indexes = None
else:
indexes = {k: v for k, v in self._indexes.items() if k in coords}
return DataArray(variable, coords, name=name, indexes=indexes, fastpath=True)
def __copy__(self) -> "Dataset":
return self.copy(deep=False)
def __deepcopy__(self, memo=None) -> "Dataset":
# memo does nothing but is required for compatibility with
# copy.deepcopy
return self.copy(deep=True)
@property
def _attr_sources(self) -> Iterable[Mapping[Hashable, Any]]:
yield from self._item_sources
yield self.attrs
@property
def _item_sources(self) -> Iterable[Mapping[Hashable, Any]]:
yield self.data_vars
yield HybridMappingProxy(keys=self._coord_names, mapping=self.coords)
# virtual coordinates
yield HybridMappingProxy(keys=self.dims, mapping=self)
# uses empty dict -- everything here can already be found in self.coords.
yield HybridMappingProxy(keys=self._level_coords, mapping={})
def __contains__(self, key: object) -> bool:
return key in self._variables
def __len__(self) -> int:
return len(self.data_vars)
def __bool__(self) -> bool:
return bool(self.data_vars)
def __iter__(self) -> Iterator[Hashable]:
return iter(self.data_vars)
def __array__(self, dtype=None):
raise TypeError(
"cannot directly convert an xarray.Dataset into a "
"numpy array. Instead, create an xarray.DataArray "
"first, either with indexing on the Dataset or by "
"invoking the `to_array()` method."
)
@property
def nbytes(self) -> int:
return sum(v.nbytes for v in self.variables.values())
@property
def loc(self) -> _LocIndexer:
return _LocIndexer(self)
# FIXME https://github.com/python/mypy/issues/7328
@overload
def __getitem__(self, key: Mapping) -> "Dataset": # type: ignore[misc]
...
@overload
def __getitem__(self, key: Hashable) -> "DataArray": # type: ignore[misc]
...
@overload
def __getitem__(self, key: Any) -> "Dataset":
...
def __getitem__(self, key):
if utils.is_dict_like(key):
return self.isel(**cast(Mapping, key))
if hashable(key):
return self._construct_dataarray(key)
else:
return self._copy_listed(np.asarray(key))
def __setitem__(self, key: Hashable, value) -> None:
if utils.is_dict_like(key):
raise NotImplementedError(
"cannot yet use a dictionary as a key to set Dataset values"
)
self.update({key: value})
def __delitem__(self, key: Hashable) -> None:
del self._variables[key]
self._coord_names.discard(key)
if key in self.indexes:
assert self._indexes is not None
del self._indexes[key]
self._dims = calculate_dimensions(self._variables)
# mutable objects should not be hashable
# https://github.com/python/mypy/issues/4266
__hash__ = None # type: ignore[assignment]
def _all_compat(self, other: "Dataset", compat_str: str) -> bool:
# some stores (e.g., scipy) do not seem to preserve order, so don't
def compat(x: Variable, y: Variable) -> bool:
return getattr(x, compat_str)(y)
return self._coord_names == other._coord_names and utils.dict_equiv(
self._variables, other._variables, compat=compat
)
def broadcast_equals(self, other: "Dataset") -> bool:
try:
return self._all_compat(other, "broadcast_equals")
except (TypeError, AttributeError):
return False
def equals(self, other: "Dataset") -> bool:
try:
return self._all_compat(other, "equals")
except (TypeError, AttributeError):
return False
def identical(self, other: "Dataset") -> bool:
try:
return utils.dict_equiv(self.attrs, other.attrs) and self._all_compat(
other, "identical"
)
except (TypeError, AttributeError):
return False
@property
def indexes(self) -> Indexes:
if self._indexes is None:
self._indexes = default_indexes(self._variables, self._dims)
return Indexes(self._indexes)
@property
def coords(self) -> DatasetCoordinates:
return DatasetCoordinates(self)
@property
def data_vars(self) -> DataVariables:
return DataVariables(self)
def set_coords(self, names: "Union[Hashable, Iterable[Hashable]]") -> "Dataset":
if isinstance(names, str) or not isinstance(names, Iterable):
names = [names]
else:
names = list(names)
self._assert_all_in_dataset(names)
obj = self.copy()
obj._coord_names.update(names)
return obj
def reset_coords(
self,
names: "Union[Hashable, Iterable[Hashable], None]" = None,
drop: bool = False,
) -> "Dataset":
if names is None:
names = self._coord_names - set(self.dims)
else:
if isinstance(names, str) or not isinstance(names, Iterable):
names = [names]
else:
names = list(names)
self._assert_all_in_dataset(names)
bad_coords = set(names) & set(self.dims)
if bad_coords:
raise ValueError(
"cannot remove index coordinates with reset_coords: %s" % bad_coords
)
obj = self.copy()
obj._coord_names.difference_update(names)
if drop:
for name in names:
del obj._variables[name]
return obj
def dump_to_store(self, store: "AbstractDataStore", **kwargs) -> None:
from ..backends.api import dump_to_store
dump_to_store(self, store, **kwargs)
def to_netcdf(
self,
path=None,
mode: str = "w",
format: str = None,
group: str = None,
engine: str = None,
encoding: Mapping = None,
unlimited_dims: Iterable[Hashable] = None,
compute: bool = True,
invalid_netcdf: bool = False,
) -> Union[bytes, "Delayed", None]:
if encoding is None:
encoding = {}
from ..backends.api import to_netcdf
return to_netcdf(
self,
path,
mode,
format=format,
group=group,
engine=engine,
encoding=encoding,
unlimited_dims=unlimited_dims,
compute=compute,
invalid_netcdf=invalid_netcdf,
)
def to_zarr(
self,
store: Union[MutableMapping, str, Path] = None,
chunk_store: Union[MutableMapping, str, Path] = None,
mode: str = None,
synchronizer=None,
group: str = None,
encoding: Mapping = None,
compute: bool = True,
consolidated: bool = False,
append_dim: Hashable = None,
region: Mapping[str, slice] = None,
) -> "ZarrStore":
from ..backends.api import to_zarr
if encoding is None:
encoding = {}
return to_zarr(
self,
store=store,
chunk_store=chunk_store,
mode=mode,
synchronizer=synchronizer,
group=group,
encoding=encoding,
compute=compute,
consolidated=consolidated,
append_dim=append_dim,
region=region,
)
def __repr__(self) -> str:
return formatting.dataset_repr(self)
def _repr_html_(self):
if OPTIONS["display_style"] == "text":
return f"<pre>{escape(repr(self))}</pre>"
return formatting_html.dataset_repr(self)
def info(self, buf=None) -> None:
if buf is None:
buf = sys.stdout
lines = []
lines.append("xarray.Dataset {")
lines.append("dimensions:")
for name, size in self.dims.items():
lines.append(f"\t{name} = {size} ;")
lines.append("\nvariables:")
for name, da in self.variables.items():
dims = ", ".join(da.dims)
lines.append(f"\t{da.dtype} {name}({dims}) ;")
for k, v in da.attrs.items():
lines.append(f"\t\t{name}:{k} = {v} ;")
lines.append("\n// global attributes:")
for k, v in self.attrs.items():
lines.append(f"\t:{k} = {v} ;")
lines.append("}")
buf.write("\n".join(lines))
@property
def chunks(self) -> Mapping[Hashable, Tuple[int, ...]]:
chunks: Dict[Hashable, Tuple[int, ...]] = {}
for v in self.variables.values():
if v.chunks is not None:
for dim, c in zip(v.dims, v.chunks):
if dim in chunks and c != chunks[dim]:
raise ValueError(
f"Object has inconsistent chunks along dimension {dim}. "
"This can be fixed by calling unify_chunks()."
)
chunks[dim] = c
return Frozen(SortedKeysDict(chunks))
def chunk(
self,
chunks: Union[
Number,
str,
Mapping[Hashable, Union[None, Number, str, Tuple[Number, ...]]],
] = {},
name_prefix: str = "xarray-",
token: str = None,
lock: bool = False,
) -> "Dataset":
if chunks is None:
warnings.warn(
"None value for 'chunks' is deprecated. "
"It will raise an error in the future. Use instead '{}'",
category=FutureWarning,
)
chunks = {}
if isinstance(chunks, (Number, str)):
chunks = dict.fromkeys(self.dims, chunks)
bad_dims = chunks.keys() - self.dims.keys()
if bad_dims:
raise ValueError(
"some chunks keys are not dimensions on this " "object: %s" % bad_dims
)
variables = {
k: _maybe_chunk(k, v, chunks, token, lock, name_prefix)
for k, v in self.variables.items()
}
return self._replace(variables)
def _validate_indexers(
self, indexers: Mapping[Hashable, Any], missing_dims: str = "raise"
) -> Iterator[Tuple[Hashable, Union[int, slice, np.ndarray, Variable]]]:
from .dataarray import DataArray
indexers = drop_dims_from_indexers(indexers, self.dims, missing_dims)
# all indexers should be int, slice, np.ndarrays, or Variable
for k, v in indexers.items():
if isinstance(v, (int, slice, Variable)):
yield k, v
elif isinstance(v, DataArray):
yield k, v.variable
elif isinstance(v, tuple):
yield k, as_variable(v)
elif isinstance(v, Dataset):
raise TypeError("cannot use a Dataset as an indexer")
elif isinstance(v, Sequence) and len(v) == 0:
yield k, np.empty((0,), dtype="int64")
else:
v = np.asarray(v)
if v.dtype.kind in "US":
index = self.indexes[k]
if isinstance(index, pd.DatetimeIndex):
v = v.astype("datetime64[ns]")
elif isinstance(index, xr.CFTimeIndex):
v = _parse_array_of_cftime_strings(v, index.date_type)
if v.ndim > 1:
raise IndexError(
"Unlabeled multi-dimensional array cannot be "
"used for indexing: {}".format(k)
)
yield k, v
def _validate_interp_indexers(
self, indexers: Mapping[Hashable, Any]
) -> Iterator[Tuple[Hashable, Variable]]:
for k, v in self._validate_indexers(indexers):
if isinstance(v, Variable):
if v.ndim == 1:
yield k, v.to_index_variable()
else:
yield k, v
elif isinstance(v, int):
yield k, Variable((), v)
elif isinstance(v, np.ndarray):
if v.ndim == 0:
yield k, Variable((), v)
elif v.ndim == 1:
yield k, IndexVariable((k,), v)
else:
raise AssertionError() # Already tested by _validate_indexers
else:
raise TypeError(type(v))
def _get_indexers_coords_and_indexes(self, indexers):
from .dataarray import DataArray
coords_list = []
for k, v in indexers.items():
if isinstance(v, DataArray):
if v.dtype.kind == "b":
if v.ndim != 1: # we only support 1-d boolean array
raise ValueError(
"{:d}d-boolean array is used for indexing along "
"dimension {!r}, but only 1d boolean arrays are "
"supported.".format(v.ndim, k)
)
# Make sure in case of boolean DataArray, its
# coordinate also should be indexed.
v_coords = v[v.values.nonzero()[0]].coords
else:
v_coords = v.coords
coords_list.append(v_coords)
# we don't need to call align() explicitly or check indexes for
coords, indexes = merge_coordinates_without_align(coords_list)
assert_coordinate_consistent(self, coords)
attached_coords = {k: v for k, v in coords.items() if k not in self._variables}
attached_indexes = {
k: v for k, v in indexes.items() if k not in self._variables
}
return attached_coords, attached_indexes
def isel(
self,
indexers: Mapping[Hashable, Any] = None,
drop: bool = False,
missing_dims: str = "raise",
**indexers_kwargs: Any,
) -> "Dataset":
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "isel")
if any(is_fancy_indexer(idx) for idx in indexers.values()):
return self._isel_fancy(indexers, drop=drop, missing_dims=missing_dims)
indexers = drop_dims_from_indexers(indexers, self.dims, missing_dims)
variables = {}
dims: Dict[Hashable, Tuple[int, ...]] = {}
coord_names = self._coord_names.copy()
indexes = self._indexes.copy() if self._indexes is not None else None
for var_name, var_value in self._variables.items():
var_indexers = {k: v for k, v in indexers.items() if k in var_value.dims}
if var_indexers:
var_value = var_value.isel(var_indexers)
if drop and var_value.ndim == 0 and var_name in coord_names:
coord_names.remove(var_name)
if indexes:
indexes.pop(var_name, None)
continue
if indexes and var_name in indexes:
if var_value.ndim == 1:
indexes[var_name] = var_value.to_index()
else:
del indexes[var_name]
variables[var_name] = var_value
dims.update(zip(var_value.dims, var_value.shape))
return self._construct_direct(
variables=variables,
coord_names=coord_names,
dims=dims,
attrs=self._attrs,
indexes=indexes,
encoding=self._encoding,
close=self._close,
)
def _isel_fancy(
self,
indexers: Mapping[Hashable, Any],
*,
drop: bool,
missing_dims: str = "raise",
) -> "Dataset":
# Note: we need to preserve the original indexers variable in order to merge the
# coords below
indexers_list = list(self._validate_indexers(indexers, missing_dims))
variables: Dict[Hashable, Variable] = {}
indexes: Dict[Hashable, pd.Index] = {}
for name, var in self.variables.items():
var_indexers = {k: v for k, v in indexers_list if k in var.dims}
if drop and name in var_indexers:
continue # drop this variable
if name in self.indexes:
new_var, new_index = isel_variable_and_index(
name, var, self.indexes[name], var_indexers
)
if new_index is not None:
indexes[name] = new_index
elif var_indexers:
new_var = var.isel(indexers=var_indexers)
else:
new_var = var.copy(deep=False)
variables[name] = new_var
coord_names = self._coord_names & variables.keys()
selected = self._replace_with_new_dims(variables, coord_names, indexes)
# Extract coordinates from indexers
coord_vars, new_indexes = selected._get_indexers_coords_and_indexes(indexers)
variables.update(coord_vars)
indexes.update(new_indexes)
coord_names = self._coord_names & variables.keys() | coord_vars.keys()
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def sel(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
drop: bool = False,
**indexers_kwargs: Any,
) -> "Dataset":
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "sel")
pos_indexers, new_indexes = remap_label_indexers(
self, indexers=indexers, method=method, tolerance=tolerance
)
result = self.isel(indexers=pos_indexers, drop=drop)
return result._overwrite_indexes(new_indexes)
def head(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
if not indexers_kwargs:
if indexers is None:
indexers = 5
if not isinstance(indexers, int) and not is_dict_like(indexers):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "head")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
indexers_slices = {k: slice(val) for k, val in indexers.items()}
return self.isel(indexers_slices)
def tail(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
if not indexers_kwargs:
if indexers is None:
indexers = 5
if not isinstance(indexers, int) and not is_dict_like(indexers):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "tail")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
indexers_slices = {
k: slice(-val, None) if val != 0 else slice(val)
for k, val in indexers.items()
}
return self.isel(indexers_slices)
def thin(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
if (
not indexers_kwargs
and not isinstance(indexers, int)
and not is_dict_like(indexers)
):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "thin")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
elif v == 0:
raise ValueError("step cannot be zero")
indexers_slices = {k: slice(None, None, val) for k, val in indexers.items()}
return self.isel(indexers_slices)
def broadcast_like(
self, other: Union["Dataset", "DataArray"], exclude: Iterable[Hashable] = None
) -> "Dataset":
if exclude is None:
exclude = set()
else:
exclude = set(exclude)
args = align(other, self, join="outer", copy=False, exclude=exclude)
dims_map, common_coords = _get_broadcast_dims_map_common_coords(args, exclude)
return _broadcast_helper(args[1], exclude, dims_map, common_coords)
def reindex_like(
self,
other: Union["Dataset", "DataArray"],
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
) -> "Dataset":
indexers = alignment.reindex_like_indexers(self, other)
return self.reindex(
indexers=indexers,
method=method,
copy=copy,
fill_value=fill_value,
tolerance=tolerance,
)
def reindex(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
**indexers_kwargs: Any,
) -> "Dataset":
return self._reindex(
indexers,
method,
tolerance,
copy,
fill_value,
sparse=False,
**indexers_kwargs,
)
def _reindex(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
sparse: bool = False,
**indexers_kwargs: Any,
) -> "Dataset":
indexers = utils.either_dict_or_kwargs(indexers, indexers_kwargs, "reindex")
bad_dims = [d for d in indexers if d not in self.dims]
if bad_dims:
raise ValueError("invalid reindex dimensions: %s" % bad_dims)
variables, indexes = alignment.reindex_variables(
self.variables,
self.sizes,
self.indexes,
indexers,
method,
tolerance,
copy=copy,
fill_value=fill_value,
sparse=sparse,
)
coord_names = set(self._coord_names)
coord_names.update(indexers)
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def interp(
self,
coords: Mapping[Hashable, Any] = None,
method: str = "linear",
assume_sorted: bool = False,
kwargs: Mapping[str, Any] = None,
**coords_kwargs: Any,
) -> "Dataset":
from . import missing
if kwargs is None:
kwargs = {}
coords = either_dict_or_kwargs(coords, coords_kwargs, "interp")
indexers = dict(self._validate_interp_indexers(coords))
if coords:
# This avoids broadcasting over coordinates that are both in
# the original array AND in the indexing array. It essentially
# forces interpolation along the shared coordinates.
sdims = (
set(self.dims)
.intersection(*[set(nx.dims) for nx in indexers.values()])
.difference(coords.keys())
)
indexers.update({d: self.variables[d] for d in sdims})
obj = self if assume_sorted else self.sortby([k for k in coords])
def maybe_variable(obj, k):
# workaround to get variable for dimension without coordinate.
try:
return obj._variables[k]
except KeyError:
return as_variable((k, range(obj.dims[k])))
def _validate_interp_indexer(x, new_x):
# In the case of datetimes, the restrictions placed on indexers
# used with interp are stronger than those which are placed on
# isel, so we need an additional check after _validate_indexers.
if _contains_datetime_like_objects(
x
) and not _contains_datetime_like_objects(new_x):
raise TypeError(
"When interpolating over a datetime-like "
"coordinate, the coordinates to "
"interpolate to must be either datetime "
"strings or datetimes. "
"Instead got\n{}".format(new_x)
)
return x, new_x
variables: Dict[Hashable, Variable] = {}
for name, var in obj._variables.items():
if name in indexers:
continue
if var.dtype.kind in "uifc":
var_indexers = {
k: _validate_interp_indexer(maybe_variable(obj, k), v)
for k, v in indexers.items()
if k in var.dims
}
variables[name] = missing.interp(var, var_indexers, method, **kwargs)
elif all(d not in indexers for d in var.dims):
# keep unrelated object array
variables[name] = var
coord_names = obj._coord_names & variables.keys()
indexes = {k: v for k, v in obj.indexes.items() if k not in indexers}
selected = self._replace_with_new_dims(
variables.copy(), coord_names, indexes=indexes
)
# attach indexer as coordinate
variables.update(indexers)
for k, v in indexers.items():
assert isinstance(v, Variable)
if v.dims == (k,):
indexes[k] = v.to_index()
# Extract coordinates from indexers
coord_vars, new_indexes = selected._get_indexers_coords_and_indexes(coords)
variables.update(coord_vars)
indexes.update(new_indexes)
coord_names = obj._coord_names & variables.keys() | coord_vars.keys()
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def interp_like(
self,
other: Union["Dataset", "DataArray"],
method: str = "linear",
assume_sorted: bool = False,
kwargs: Mapping[str, Any] = None,
) -> "Dataset":
if kwargs is None:
kwargs = {}
coords = alignment.reindex_like_indexers(self, other)
numeric_coords: Dict[Hashable, pd.Index] = {}
object_coords: Dict[Hashable, pd.Index] = {}
for k, v in coords.items():
if v.dtype.kind in "uifcMm":
numeric_coords[k] = v
else:
object_coords[k] = v
ds = self
if object_coords:
# We do not support interpolation along object coordinate.
# reindex instead.
ds = self.reindex(object_coords)
return ds.interp(numeric_coords, method, assume_sorted, kwargs)
# Helper methods for rename()
def _rename_vars(self, name_dict, dims_dict):
variables = {}
coord_names = set()
for k, v in self.variables.items():
var = v.copy(deep=False)
var.dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
name = name_dict.get(k, k)
if name in variables:
raise ValueError(f"the new name {name!r} conflicts")
variables[name] = var
if k in self._coord_names:
coord_names.add(name)
return variables, coord_names
def _rename_dims(self, name_dict):
return {name_dict.get(k, k): v for k, v in self.dims.items()}
def _rename_indexes(self, name_dict, dims_set):
if self._indexes is None:
return None
indexes = {}
for k, v in self.indexes.items():
new_name = name_dict.get(k, k)
if new_name not in dims_set:
continue
if isinstance(v, pd.MultiIndex):
new_names = [name_dict.get(k, k) for k in v.names]
index = v.rename(names=new_names)
else:
index = v.rename(new_name)
indexes[new_name] = index
return indexes
def _rename_all(self, name_dict, dims_dict):
variables, coord_names = self._rename_vars(name_dict, dims_dict)
dims = self._rename_dims(dims_dict)
indexes = self._rename_indexes(name_dict, dims.keys())
return variables, coord_names, dims, indexes
def rename(
self,
name_dict: Mapping[Hashable, Hashable] = None,
**names: Hashable,
) -> "Dataset":
name_dict = either_dict_or_kwargs(name_dict, names, "rename")
for k in name_dict.keys():
if k not in self and k not in self.dims:
raise ValueError(
"cannot rename %r because it is not a "
"variable or dimension in this dataset" % k
)
variables, coord_names, dims, indexes = self._rename_all(
name_dict=name_dict, dims_dict=name_dict
)
assert_unique_multiindex_level_names(variables)
return self._replace(variables, coord_names, dims=dims, indexes=indexes)
def rename_dims(
self, dims_dict: Mapping[Hashable, Hashable] = None, **dims: Hashable
) -> "Dataset":
dims_dict = either_dict_or_kwargs(dims_dict, dims, "rename_dims")
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError(
"cannot rename %r because it is not a "
"dimension in this dataset" % k
)
if v in self.dims or v in self:
raise ValueError(
f"Cannot rename {k} to {v} because {v} already exists. "
"Try using swap_dims instead."
)
variables, coord_names, sizes, indexes = self._rename_all(
name_dict={}, dims_dict=dims_dict
)
return self._replace(variables, coord_names, dims=sizes, indexes=indexes)
def rename_vars(
self, name_dict: Mapping[Hashable, Hashable] = None, **names: Hashable
) -> "Dataset":
name_dict = either_dict_or_kwargs(name_dict, names, "rename_vars")
for k in name_dict:
if k not in self:
raise ValueError(
"cannot rename %r because it is not a "
"variable or coordinate in this dataset" % k
)
variables, coord_names, dims, indexes = self._rename_all(
name_dict=name_dict, dims_dict={}
)
return self._replace(variables, coord_names, dims=dims, indexes=indexes)
def swap_dims(
self, dims_dict: Mapping[Hashable, Hashable] = None, **dims_kwargs
) -> "Dataset":
# TODO: deprecate this method in favor of a (less confusing)
# rename_dims() method that only renames dimensions.
dims_dict = either_dict_or_kwargs(dims_dict, dims_kwargs, "swap_dims")
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError(
"cannot swap from dimension %r because it is "
"not an existing dimension" % k
)
if v in self.variables and self.variables[v].dims != (k,):
raise ValueError(
"replacement dimension %r is not a 1D "
"variable along the old dimension %r" % (v, k)
)
result_dims = {dims_dict.get(dim, dim) for dim in self.dims}
coord_names = self._coord_names.copy()
coord_names.update({dim for dim in dims_dict.values() if dim in self.variables})
variables: Dict[Hashable, Variable] = {}
indexes: Dict[Hashable, pd.Index] = {}
for k, v in self.variables.items():
dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
if k in result_dims:
var = v.to_index_variable()
if k in self.indexes:
indexes[k] = self.indexes[k]
else:
new_index = var.to_index()
if new_index.nlevels == 1:
# make sure index name matches dimension name
new_index = new_index.rename(k)
indexes[k] = new_index
else:
var = v.to_base_variable()
var.dims = dims
variables[k] = var
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def expand_dims(
self,
dim: Union[None, Hashable, Sequence[Hashable], Mapping[Hashable, Any]] = None,
axis: Union[None, int, Sequence[int]] = None,
**dim_kwargs: Any,
) -> "Dataset":
if dim is None:
pass
elif isinstance(dim, Mapping):
# We're later going to modify dim in place; don't tamper with
# the input
dim = dict(dim)
elif isinstance(dim, int):
raise TypeError(
"dim should be hashable or sequence of hashables or mapping"
)
elif isinstance(dim, str) or not isinstance(dim, Sequence):
dim = {dim: 1}
elif isinstance(dim, Sequence):
if len(dim) != len(set(dim)):
raise ValueError("dims should not contain duplicate values.")
dim = {d: 1 for d in dim}
dim = either_dict_or_kwargs(dim, dim_kwargs, "expand_dims")
assert isinstance(dim, MutableMapping)
if axis is None:
axis = list(range(len(dim)))
elif not isinstance(axis, Sequence):
axis = [axis]
if len(dim) != len(axis):
raise ValueError("lengths of dim and axis should be identical.")
for d in dim:
if d in self.dims:
raise ValueError(f"Dimension {d} already exists.")
if d in self._variables and not utils.is_scalar(self._variables[d]):
raise ValueError(
"{dim} already exists as coordinate or"
" variable name.".format(dim=d)
)
variables: Dict[Hashable, Variable] = {}
coord_names = self._coord_names.copy()
# If dim is a dict, then ensure that the values are either integers
# or iterables.
for k, v in dim.items():
if hasattr(v, "__iter__"):
# If the value for the new dimension is an iterable, then
# save the coordinates to the variables dict, and set the
# value within the dim dict to the length of the iterable
# for later use.
variables[k] = xr.IndexVariable((k,), v)
coord_names.add(k)
dim[k] = variables[k].size
elif isinstance(v, int):
pass # Do nothing if the dimensions value is just an int
else:
raise TypeError(
"The value of new dimension {k} must be "
"an iterable or an int".format(k=k)
)
for k, v in self._variables.items():
if k not in dim:
if k in coord_names: # Do not change coordinates
variables[k] = v
else:
result_ndim = len(v.dims) + len(axis)
for a in axis:
if a < -result_ndim or result_ndim - 1 < a:
raise IndexError(
f"Axis {a} of variable {k} is out of bounds of the "
f"expanded dimension size {result_ndim}"
)
axis_pos = [a if a >= 0 else result_ndim + a for a in axis]
if len(axis_pos) != len(set(axis_pos)):
raise ValueError("axis should not contain duplicate values")
# We need to sort them to make sure `axis` equals to the
# axis positions of the result array.
zip_axis_dim = sorted(zip(axis_pos, dim.items()))
all_dims = list(zip(v.dims, v.shape))
for d, c in zip_axis_dim:
all_dims.insert(d, c)
variables[k] = v.set_dims(dict(all_dims))
else:
# If dims includes a label of a non-dimension coordinate,
# it will be promoted to a 1D coordinate with a single value.
variables[k] = v.set_dims(k).to_index_variable()
new_dims = self._dims.copy()
new_dims.update(dim)
return self._replace_vars_and_dims(
variables, dims=new_dims, coord_names=coord_names
)
def set_index(
self,
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]] = None,
append: bool = False,
**indexes_kwargs: Union[Hashable, Sequence[Hashable]],
) -> "Dataset":
indexes = either_dict_or_kwargs(indexes, indexes_kwargs, "set_index")
variables, coord_names = merge_indexes(
indexes, self._variables, self._coord_names, append=append
)
return self._replace_vars_and_dims(variables, coord_names=coord_names)
def reset_index(
self,
dims_or_levels: Union[Hashable, Sequence[Hashable]],
drop: bool = False,
) -> "Dataset":
variables, coord_names = split_indexes(
dims_or_levels,
self._variables,
self._coord_names,
cast(Mapping[Hashable, Hashable], self._level_coords),
drop=drop,
)
return self._replace_vars_and_dims(variables, coord_names=coord_names)
def reorder_levels(
self,
dim_order: Mapping[Hashable, Sequence[int]] = None,
**dim_order_kwargs: Sequence[int],
) -> "Dataset":
dim_order = either_dict_or_kwargs(dim_order, dim_order_kwargs, "reorder_levels")
variables = self._variables.copy()
indexes = dict(self.indexes)
for dim, order in dim_order.items():
coord = self._variables[dim]
index = self.indexes[dim]
if not isinstance(index, pd.MultiIndex):
raise ValueError(f"coordinate {dim} has no MultiIndex")
new_index = index.reorder_levels(order)
variables[dim] = IndexVariable(coord.dims, new_index)
indexes[dim] = new_index
return self._replace(variables, indexes=indexes)
def _stack_once(self, dims, new_dim):
if ... in dims:
dims = list(infix_dims(dims, self.dims))
variables = {}
for name, var in self.variables.items():
if name not in dims:
if any(d in var.dims for d in dims):
add_dims = [d for d in dims if d not in var.dims]
vdims = list(var.dims) + add_dims
shape = [self.dims[d] for d in vdims]
exp_var = var.set_dims(vdims, shape)
stacked_var = exp_var.stack(**{new_dim: dims})
variables[name] = stacked_var
else:
variables[name] = var.copy(deep=False)
# consider dropping levels that are unused?
levels = [self.get_index(dim) for dim in dims]
idx = utils.multiindex_from_product_levels(levels, names=dims)
variables[new_dim] = IndexVariable(new_dim, idx)
coord_names = set(self._coord_names) - set(dims) | {new_dim}
indexes = {k: v for k, v in self.indexes.items() if k not in dims}
indexes[new_dim] = idx
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def stack(
self,
dimensions: Mapping[Hashable, Sequence[Hashable]] = None,
**dimensions_kwargs: Sequence[Hashable],
) -> "Dataset":
dimensions = either_dict_or_kwargs(dimensions, dimensions_kwargs, "stack")
result = self
for new_dim, dims in dimensions.items():
result = result._stack_once(dims, new_dim)
return result
def to_stacked_array(
self,
new_dim: Hashable,
sample_dims: Sequence[Hashable],
variable_dim: str = "variable",
name: Hashable = None,
) -> "DataArray":
stacking_dims = tuple(dim for dim in self.dims if dim not in sample_dims)
for variable in self:
dims = self[variable].dims
dims_include_sample_dims = set(sample_dims) <= set(dims)
if not dims_include_sample_dims:
raise ValueError(
"All variables in the dataset must contain the "
"dimensions {}.".format(dims)
)
def ensure_stackable(val):
assign_coords = {variable_dim: val.name}
for dim in stacking_dims:
if dim not in val.dims:
assign_coords[dim] = None
expand_dims = set(stacking_dims).difference(set(val.dims))
expand_dims.add(variable_dim)
# must be list for .expand_dims
expand_dims = list(expand_dims)
return (
val.assign_coords(**assign_coords)
.expand_dims(expand_dims)
.stack({new_dim: (variable_dim,) + stacking_dims})
)
# concatenate the arrays
stackable_vars = [ensure_stackable(self[key]) for key in self.data_vars]
data_array = xr.concat(stackable_vars, dim=new_dim)
# coerce the levels of the MultiIndex to have the same type as the
# input dimensions. This code is messy, so it might be better to just
# input a dummy value for the singleton dimension.
idx = data_array.indexes[new_dim]
levels = [idx.levels[0]] + [
level.astype(self[level.name].dtype) for level in idx.levels[1:]
]
new_idx = idx.set_levels(levels)
data_array[new_dim] = IndexVariable(new_dim, new_idx)
if name is not None:
data_array.name = name
return data_array
def _unstack_once(self, dim: Hashable, fill_value) -> "Dataset":
index = self.get_index(dim)
index = remove_unused_levels_categories(index)
variables: Dict[Hashable, Variable] = {}
indexes = {k: v for k, v in self.indexes.items() if k != dim}
for name, var in self.variables.items():
if name != dim:
if dim in var.dims:
if isinstance(fill_value, Mapping):
fill_value_ = fill_value[name]
else:
fill_value_ = fill_value
variables[name] = var._unstack_once(
index=index, dim=dim, fill_value=fill_value_
)
else:
variables[name] = var
for name, lev in zip(index.names, index.levels):
variables[name] = IndexVariable(name, lev)
indexes[name] = lev
coord_names = set(self._coord_names) - {dim} | set(index.names)
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def _unstack_full_reindex(
self, dim: Hashable, fill_value, sparse: bool
) -> "Dataset":
index = self.get_index(dim)
index = remove_unused_levels_categories(index)
full_idx = pd.MultiIndex.from_product(index.levels, names=index.names)
# take a shortcut in case the MultiIndex was not modified.
if index.equals(full_idx):
obj = self
else:
obj = self._reindex(
{dim: full_idx}, copy=False, fill_value=fill_value, sparse=sparse
)
new_dim_names = index.names
new_dim_sizes = [lev.size for lev in index.levels]
variables: Dict[Hashable, Variable] = {}
indexes = {k: v for k, v in self.indexes.items() if k != dim}
for name, var in obj.variables.items():
if name != dim:
if dim in var.dims:
new_dims = dict(zip(new_dim_names, new_dim_sizes))
variables[name] = var.unstack({dim: new_dims})
else:
variables[name] = var
for name, lev in zip(new_dim_names, index.levels):
variables[name] = IndexVariable(name, lev)
indexes[name] = lev
coord_names = set(self._coord_names) - {dim} | set(new_dim_names)
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def unstack(
self,
dim: Union[Hashable, Iterable[Hashable]] = None,
fill_value: Any = dtypes.NA,
sparse: bool = False,
) -> "Dataset":
if dim is None:
dims = [
d for d in self.dims if isinstance(self.get_index(d), pd.MultiIndex)
]
else:
if isinstance(dim, str) or not isinstance(dim, Iterable):
dims = [dim]
else:
dims = list(dim)
missing_dims = [d for d in dims if d not in self.dims]
if missing_dims:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dims
)
non_multi_dims = [
d for d in dims if not isinstance(self.get_index(d), pd.MultiIndex)
]
if non_multi_dims:
raise ValueError(
"cannot unstack dimensions that do not "
"have a MultiIndex: %s" % non_multi_dims
)
result = self.copy(deep=False)
for dim in dims:
if (
# Dask arrays don't support assignment by index, which the fast unstack
_duck_dask_array(v.data) for v in self.variables.values())
# it)
# https://github.com/pydata/sparse/issues/422
or any(
isinstance(v.data, sparse_array_type)
for v in self.variables.values()
)
or sparse
# numpy full_like only added `shape` in 1.17
or LooseVersion(np.__version__) < LooseVersion("1.17")
# Until https://github.com/pydata/xarray/pull/4751 is resolved,
# we check explicitly whether it's a numpy array. Once that is
= result._unstack_full_reindex(dim, fill_value, sparse)
else:
result = result._unstack_once(dim, fill_value)
return result
def update(self, other: "CoercibleMapping") -> "Dataset":
merge_result = dataset_update_method(self, other)
return self._replace(inplace=True, **merge_result._asdict())
def merge(
self,
other: Union["CoercibleMapping", "DataArray"],
overwrite_vars: Union[Hashable, Iterable[Hashable]] = frozenset(),
compat: str = "no_conflicts",
join: str = "outer",
fill_value: Any = dtypes.NA,
combine_attrs: str = "override",
) -> "Dataset":
other = other.to_dataset() if isinstance(other, xr.DataArray) else other
merge_result = dataset_merge_method(
self,
other,
overwrite_vars=overwrite_vars,
compat=compat,
join=join,
fill_value=fill_value,
combine_attrs=combine_attrs,
)
return self._replace(**merge_result._asdict())
def _assert_all_in_dataset(
self, names: Iterable[Hashable], virtual_okay: bool = False
) -> None:
bad_names = set(names) - set(self._variables)
if virtual_okay:
bad_names -= self.virtual_variables
if bad_names:
raise ValueError(
"One or more of the specified variables "
"cannot be found in this dataset"
)
def drop_vars(
self, names: Union[Hashable, Iterable[Hashable]], *, errors: str = "raise"
) -> "Dataset":
if is_scalar(names) or not isinstance(names, Iterable):
names = {names}
else:
names = set(names)
if errors == "raise":
self._assert_all_in_dataset(names)
variables = {k: v for k, v in self._variables.items() if k not in names}
coord_names = {k for k in self._coord_names if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k not in names}
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def drop(self, labels=None, dim=None, *, errors="raise", **labels_kwargs):
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
if is_dict_like(labels) and not isinstance(labels, dict):
warnings.warn(
"dropping coordinates using `drop` is be deprecated; use drop_vars.",
FutureWarning,
stacklevel=2,
)
return self.drop_vars(labels, errors=errors)
if labels_kwargs or isinstance(labels, dict):
if dim is not None:
raise ValueError("cannot specify dim and dict-like arguments.")
labels = either_dict_or_kwargs(labels, labels_kwargs, "drop")
if dim is None and (is_scalar(labels) or isinstance(labels, Iterable)):
warnings.warn(
"dropping variables using `drop` will be deprecated; using drop_vars is encouraged.",
PendingDeprecationWarning,
stacklevel=2,
)
return self.drop_vars(labels, errors=errors)
if dim is not None:
warnings.warn(
"dropping labels using list-like labels is deprecated; using "
"dict-like arguments with `drop_sel`, e.g. `ds.drop_sel(dim=[labels]).",
DeprecationWarning,
stacklevel=2,
)
return self.drop_sel({dim: labels}, errors=errors, **labels_kwargs)
warnings.warn(
"dropping labels using `drop` will be deprecated; using drop_sel is encouraged.",
PendingDeprecationWarning,
stacklevel=2,
)
return self.drop_sel(labels, errors=errors)
def drop_sel(self, labels=None, *, errors="raise", **labels_kwargs):
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
labels = either_dict_or_kwargs(labels, labels_kwargs, "drop_sel")
ds = self
for dim, labels_for_dim in labels.items():
# is a large numpy array
if utils.is_scalar(labels_for_dim):
labels_for_dim = [labels_for_dim]
labels_for_dim = np.asarray(labels_for_dim)
try:
index = self.get_index(dim)
except KeyError:
raise ValueError("dimension %r does not have coordinate labels" % dim)
new_index = index.drop(labels_for_dim, errors=errors)
ds = ds.loc[{dim: new_index}]
return ds
def drop_isel(self, indexers=None, **indexers_kwargs):
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "drop_isel")
ds = self
dimension_index = {}
for dim, pos_for_dim in indexers.items():
# Don't cast to set, as it would harm performance when labels
if utils.is_scalar(pos_for_dim):
pos_for_dim = [pos_for_dim]
pos_for_dim = np.asarray(pos_for_dim)
index = self.get_index(dim)
new_index = index.delete(pos_for_dim)
dimension_index[dim] = new_index
ds = ds.loc[dimension_index]
return ds
def drop_dims(
self, drop_dims: Union[Hashable, Iterable[Hashable]], *, errors: str = "raise"
) -> "Dataset":
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
if isinstance(drop_dims, str) or not isinstance(drop_dims, Iterable):
drop_dims = {drop_dims}
else:
drop_dims = set(drop_dims)
if errors == "raise":
missing_dims = drop_dims - set(self.dims)
if missing_dims:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dims
)
drop_vars = {k for k, v in self._variables.items() if set(v.dims) & drop_dims}
return self.drop_vars(drop_vars)
def transpose(self, *dims: Hashable) -> "Dataset":
if dims:
if set(dims) ^ set(self.dims) and ... not in dims:
raise ValueError(
"arguments to transpose (%s) must be "
"permuted dataset dimensions (%s)" % (dims, tuple(self.dims))
)
ds = self.copy()
for name, var in self._variables.items():
var_dims = tuple(dim for dim in dims if dim in (var.dims + (...,)))
ds._variables[name] = var.transpose(*var_dims)
return ds
def dropna(
self,
dim: Hashable,
how: str = "any",
thresh: int = None,
subset: Iterable[Hashable] = None,
):
# depending on the order of the supplied axes.
if dim not in self.dims:
raise ValueError("%s must be a single dataset dimension" % dim)
if subset is None:
subset = iter(self.data_vars)
count = np.zeros(self.dims[dim], dtype=np.int64)
size = np.int_(0) # for type checking
for k in subset:
array = self._variables[k]
if dim in array.dims:
dims = [d for d in array.dims if d != dim]
count += np.asarray(array.count(dims)) # type: ignore[attr-defined]
size += np.prod([self.dims[d] for d in dims])
if thresh is not None:
mask = count >= thresh
elif how == "any":
mask = count == size
elif how == "all":
mask = count > 0
elif how is not None:
raise ValueError("invalid how option: %s" % how)
else:
raise TypeError("must specify how or thresh")
return self.isel({dim: mask})
def fillna(self, value: Any) -> "Dataset":
if utils.is_dict_like(value):
value_keys = getattr(value, "data_vars", value).keys()
if not set(value_keys) <= set(self.data_vars.keys()):
raise ValueError(
"all variables in the argument to `fillna` "
"must be contained in the original dataset"
)
out = ops.fillna(self, value)
return out
def interpolate_na(
self,
dim: Hashable = None,
method: str = "linear",
limit: int = None,
use_coordinate: Union[bool, Hashable] = True,
max_gap: Union[
int, float, str, pd.Timedelta, np.timedelta64, datetime.timedelta
] = None,
**kwargs: Any,
) -> "Dataset":
from .missing import _apply_over_vars_with_dim, interp_na
new = _apply_over_vars_with_dim(
interp_na,
self,
dim=dim,
method=method,
limit=limit,
use_coordinate=use_coordinate,
max_gap=max_gap,
**kwargs,
)
return new
def ffill(self, dim: Hashable, limit: int = None) -> "Dataset":
from .missing import _apply_over_vars_with_dim, ffill
new = _apply_over_vars_with_dim(ffill, self, dim=dim, limit=limit)
return new
def bfill(self, dim: Hashable, limit: int = None) -> "Dataset":
from .missing import _apply_over_vars_with_dim, bfill
new = _apply_over_vars_with_dim(bfill, self, dim=dim, limit=limit)
return new
def combine_first(self, other: "Dataset") -> "Dataset":
out = ops.fillna(self, other, join="outer", dataset_join="outer")
return out
def reduce(
self,
func: Callable,
dim: Union[Hashable, Iterable[Hashable]] = None,
keep_attrs: bool = None,
keepdims: bool = False,
numeric_only: bool = False,
**kwargs: Any,
) -> "Dataset":
if "axis" in kwargs:
raise ValueError(
"passing 'axis' to Dataset reduce methods is ambiguous."
" Please use 'dim' instead."
)
if dim is None or dim is ...:
dims = set(self.dims)
elif isinstance(dim, str) or not isinstance(dim, Iterable):
dims = {dim}
else:
dims = set(dim)
missing_dimensions = [d for d in dims if d not in self.dims]
if missing_dimensions:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dimensions
)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
variables: Dict[Hashable, Variable] = {}
for name, var in self._variables.items():
reduce_dims = [d for d in var.dims if d in dims]
if name in self.coords:
if not reduce_dims:
variables[name] = var
else:
if (
not numeric_only
or np.issubdtype(var.dtype, np.number)
or (var.dtype == np.bool_)
):
if len(reduce_dims) == 1:
# unpack dimensions for the benefit of functions
# like np.argmin which can't handle tuple arguments
(reduce_dims,) = reduce_dims
elif len(reduce_dims) == var.ndim:
reduce_dims = None
variables[name] = var.reduce(
func,
dim=reduce_dims,
keep_attrs=keep_attrs,
keepdims=keepdims,
**kwargs,
)
coord_names = {k for k in self.coords if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k in variables}
attrs = self.attrs if keep_attrs else None
return self._replace_with_new_dims(
variables, coord_names=coord_names, attrs=attrs, indexes=indexes
)
def map(
self,
func: Callable,
keep_attrs: bool = None,
args: Iterable[Any] = (),
**kwargs: Any,
) -> "Dataset":
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
variables = {
k: maybe_wrap_array(v, func(v, *args, **kwargs))
for k, v in self.data_vars.items()
}
if keep_attrs:
for k, v in variables.items():
v._copy_attrs_from(self.data_vars[k])
attrs = self.attrs if keep_attrs else None
return type(self)(variables, attrs=attrs)
def apply(
self,
func: Callable,
keep_attrs: bool = None,
args: Iterable[Any] = (),
**kwargs: Any,
) -> "Dataset":
warnings.warn(
"Dataset.apply may be deprecated in the future. Using Dataset.map is encouraged",
PendingDeprecationWarning,
stacklevel=2,
)
return self.map(func, keep_attrs, args, **kwargs)
def assign(
self, variables: Mapping[Hashable, Any] = None, **variables_kwargs: Hashable
) -> "Dataset":
variables = either_dict_or_kwargs(variables, variables_kwargs, "assign")
data = self.copy()
results = data._calc_assign_results(variables)
data.update(results)
return data
def to_array(self, dim="variable", name=None):
from .dataarray import DataArray
data_vars = [self.variables[k] for k in self.data_vars]
broadcast_vars = broadcast_variables(*data_vars)
data = duck_array_ops.stack([b.data for b in broadcast_vars], axis=0)
coords = dict(self.coords)
coords[dim] = list(self.data_vars)
indexes = propagate_indexes(self._indexes)
dims = (dim,) + broadcast_vars[0].dims
return DataArray(
data, coords, dims, attrs=self.attrs, name=name, indexes=indexes
)
def _normalize_dim_order(
self, dim_order: List[Hashable] = None
) -> Dict[Hashable, int]:
if dim_order is None:
dim_order = list(self.dims)
elif set(dim_order) != set(self.dims):
raise ValueError(
"dim_order {} does not match the set of dimensions of this "
"Dataset: {}".format(dim_order, list(self.dims))
)
ordered_dims = {k: self.dims[k] for k in dim_order}
return ordered_dims
def _to_dataframe(self, ordered_dims: Mapping[Hashable, int]):
columns = [k for k in self.variables if k not in self.dims]
data = [
self._variables[k].set_dims(ordered_dims).values.reshape(-1)
for k in columns
]
index = self.coords.to_index([*ordered_dims])
return pd.DataFrame(dict(zip(columns, data)), index=index)
def to_dataframe(self, dim_order: List[Hashable] = None) -> pd.DataFrame:
ordered_dims = self._normalize_dim_order(dim_order=dim_order)
return self._to_dataframe(ordered_dims=ordered_dims)
def _set_sparse_data_from_dataframe(
self, idx: pd.Index, arrays: List[Tuple[Hashable, np.ndarray]], dims: tuple
) -> None:
from sparse import COO
if isinstance(idx, pd.MultiIndex):
coords = np.stack([np.asarray(code) for code in idx.codes], axis=0)
is_sorted = idx.is_lexsorted()
shape = tuple(lev.size for lev in idx.levels)
else:
coords = np.arange(idx.size).reshape(1, -1)
is_sorted = True
shape = (idx.size,)
for name, values in arrays:
# special case the rare exceptions (e.g., dtype=int without a
# MultiIndex).
dtype, fill_value = dtypes.maybe_promote(values.dtype)
values = np.asarray(values, dtype=dtype)
data = COO(
coords,
values,
shape,
has_duplicates=False,
sorted=is_sorted,
fill_value=fill_value,
)
self[name] = (dims, data)
def _set_numpy_data_from_dataframe(
self, idx: pd.Index, arrays: List[Tuple[Hashable, np.ndarray]], dims: tuple
) -> None:
if not isinstance(idx, pd.MultiIndex):
for name, values in arrays:
self[name] = (dims, values)
return
# NB: similar, more general logic, now exists in
# variable.unstack_once; we could consider combining them at some
# point.
shape = tuple(lev.size for lev in idx.levels)
indexer = tuple(idx.codes)
# We already verified that the MultiIndex has all unique values, so
# there are missing values if and only if the size of output arrays is
# larger that the index.
missing_values = np.prod(shape) > idx.shape[0]
for name, values in arrays:
# NumPy indexing is much faster than using DataFrame.reindex() to
# fill in missing values:
# https://stackoverflow.com/a/35049899/809705
if missing_values:
dtype, fill_value = dtypes.maybe_promote(values.dtype)
data = np.full(shape, fill_value, dtype)
else:
# If there are no missing values, keep the existing dtype
# instead of promoting to support NA, e.g., keep integer
# columns as integers.
# TODO: consider removing this special case, which doesn't
data = np.zeros(shape, values.dtype)
data[indexer] = values
self[name] = (dims, data)
@classmethod
def from_dataframe(cls, dataframe: pd.DataFrame, sparse: bool = False) -> "Dataset":
if not dataframe.columns.is_unique:
raise ValueError("cannot convert DataFrame with non-unique columns")
idx = remove_unused_levels_categories(dataframe.index)
if isinstance(idx, pd.MultiIndex) and not idx.is_unique:
raise ValueError(
"cannot convert a DataFrame with a non-unique MultiIndex into xarray"
)
# TODO: allow users to control how this casting happens, e.g., by
# forwarding arguments to pandas.Series.to_numpy?
arrays = [(k, np.asarray(v)) for k, v in dataframe.items()]
obj = cls()
if isinstance(idx, pd.MultiIndex):
dims = tuple(
name if name is not None else "level_%i" % n
for n, name in enumerate(idx.names)
)
for dim, lev in zip(dims, idx.levels):
obj[dim] = (dim, lev)
else:
index_name = idx.name if idx.name is not None else "index"
dims = (index_name,)
obj[index_name] = (dims, idx)
if sparse:
obj._set_sparse_data_from_dataframe(idx, arrays, dims)
else:
obj._set_numpy_data_from_dataframe(idx, arrays, dims)
return obj
def to_dask_dataframe(self, dim_order=None, set_index=False):
import dask.array as da
import dask.dataframe as dd
ordered_dims = self._normalize_dim_order(dim_order=dim_order)
columns = list(ordered_dims)
columns.extend(k for k in self.coords if k not in self.dims)
columns.extend(self.data_vars)
series_list = []
for name in columns:
try:
var = self.variables[name]
except KeyError:
# dimension without a matching coordinate
size = self.dims[name]
data = da.arange(size, chunks=size, dtype=np.int64)
var = Variable((name,), data)
# IndexVariable objects have a dummy .chunk() method
if isinstance(var, IndexVariable):
var = var.to_base_variable()
dask_array = var.set_dims(ordered_dims).chunk(self.chunks).data
series = dd.from_array(dask_array.reshape(-1), columns=[name])
series_list.append(series)
df = dd.concat(series_list, axis=1)
if set_index:
dim_order = [*ordered_dims]
if len(dim_order) == 1:
(dim,) = dim_order
df = df.set_index(dim)
else:
# triggers an error about multi-indexes, even if only one
# dimension is passed
df = df.set_index(dim_order)
return df
def to_dict(self, data=True):
d = {
"coords": {},
"attrs": decode_numpy_dict_values(self.attrs),
"dims": dict(self.dims),
"data_vars": {},
}
for k in self.coords:
d["coords"].update({k: self[k].variable.to_dict(data=data)})
for k in self.data_vars:
d["data_vars"].update({k: self[k].variable.to_dict(data=data)})
return d
@classmethod
def from_dict(cls, d):
if not {"coords", "data_vars"}.issubset(set(d)):
variables = d.items()
else:
import itertools
variables = itertools.chain(
d.get("coords", {}).items(), d.get("data_vars", {}).items()
)
try:
variable_dict = {
k: (v["dims"], v["data"], v.get("attrs")) for k, v in variables
}
except KeyError as e:
raise ValueError(
"cannot convert dict without the key "
"'{dims_data}'".format(dims_data=str(e.args[0]))
)
obj = cls(variable_dict)
# what if coords aren't dims?
coords = set(d.get("coords", {})) - set(d.get("dims", {}))
obj = obj.set_coords(coords)
obj.attrs.update(d.get("attrs", {}))
return obj
@staticmethod
def _unary_op(f):
@functools.wraps(f)
def func(self, *args, **kwargs):
variables = {}
keep_attrs = kwargs.pop("keep_attrs", None)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
for k, v in self._variables.items():
if k in self._coord_names:
variables[k] = v
else:
variables[k] = f(v, *args, **kwargs)
if keep_attrs:
variables[k].attrs = v._attrs
attrs = self._attrs if keep_attrs else None
return self._replace_with_new_dims(variables, attrs=attrs)
return func
@staticmethod
def _binary_op(f, reflexive=False, join=None):
@functools.wraps(f)
def func(self, other):
from .dataarray import DataArray
if isinstance(other, groupby.GroupBy):
return NotImplemented
align_type = OPTIONS["arithmetic_join"] if join is None else join
if isinstance(other, (DataArray, Dataset)):
self, other = align(self, other, join=align_type, copy=False)
g = f if not reflexive else lambda x, y: f(y, x)
ds = self._calculate_binary_op(g, other, join=align_type)
return ds
return func
@staticmethod
def _inplace_binary_op(f):
@functools.wraps(f)
def func(self, other):
from .dataarray import DataArray
if isinstance(other, groupby.GroupBy):
raise TypeError(
"in-place operations between a Dataset and "
"a grouped object are not permitted"
)
# arithmetic -- this lets us automatically align things
if isinstance(other, (DataArray, Dataset)):
other = other.reindex_like(self, copy=False)
g = ops.inplace_to_noninplace_op(f)
ds = self._calculate_binary_op(g, other, inplace=True)
self._replace_with_new_dims(
ds._variables,
ds._coord_names,
attrs=ds._attrs,
indexes=ds._indexes,
inplace=True,
)
return self
return func
def _calculate_binary_op(self, f, other, join="inner", inplace=False):
def apply_over_both(lhs_data_vars, rhs_data_vars, lhs_vars, rhs_vars):
if inplace and set(lhs_data_vars) != set(rhs_data_vars):
raise ValueError(
"datasets must have the same data variables "
"for in-place arithmetic operations: %s, %s"
% (list(lhs_data_vars), list(rhs_data_vars))
)
dest_vars = {}
for k in lhs_data_vars:
if k in rhs_data_vars:
dest_vars[k] = f(lhs_vars[k], rhs_vars[k])
elif join in ["left", "outer"]:
dest_vars[k] = f(lhs_vars[k], np.nan)
for k in rhs_data_vars:
if k not in dest_vars and join in ["right", "outer"]:
dest_vars[k] = f(rhs_vars[k], np.nan)
return dest_vars
if utils.is_dict_like(other) and not isinstance(other, Dataset):
# can't use our shortcut of doing the binary operation with
new_data_vars = apply_over_both(
self.data_vars, other, self.data_vars, other
)
return Dataset(new_data_vars)
other_coords = getattr(other, "coords", None)
ds = self.coords.merge(other_coords)
if isinstance(other, Dataset):
new_vars = apply_over_both(
self.data_vars, other.data_vars, self.variables, other.variables
)
else:
other_variable = getattr(other, "variable", other)
new_vars = {k: f(self.variables[k], other_variable) for k in self.data_vars}
ds._variables.update(new_vars)
ds._dims = calculate_dimensions(ds._variables)
return ds
def _copy_attrs_from(self, other):
self.attrs = other.attrs
for v in other.variables:
if v in self.variables:
self.variables[v].attrs = other.variables[v].attrs
def diff(self, dim, n=1, label="upper"):
if n == 0:
return self
if n < 0:
raise ValueError(f"order `n` must be non-negative but got {n}")
kwargs_start = {dim: slice(None, -1)}
kwargs_end = {dim: slice(1, None)}
if label == "upper":
kwargs_new = kwargs_end
elif label == "lower":
kwargs_new = kwargs_start
else:
raise ValueError("The 'label' argument has to be either 'upper' or 'lower'")
variables = {}
for name, var in self.variables.items():
if dim in var.dims:
if name in self.data_vars:
variables[name] = var.isel(**kwargs_end) - var.isel(**kwargs_start)
else:
variables[name] = var.isel(**kwargs_new)
else:
variables[name] = var
indexes = dict(self.indexes)
if dim in indexes:
indexes[dim] = indexes[dim][kwargs_new[dim]]
difference = self._replace_with_new_dims(variables, indexes=indexes)
if n > 1:
return difference.diff(dim, n - 1)
else:
return difference
def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs):
shifts = either_dict_or_kwargs(shifts, shifts_kwargs, "shift")
invalid = [k for k in shifts if k not in self.dims]
if invalid:
raise ValueError("dimensions %r do not exist" % invalid)
variables = {}
for name, var in self.variables.items():
if name in self.data_vars:
fill_value_ = (
fill_value.get(name, dtypes.NA)
if isinstance(fill_value, dict)
else fill_value
)
var_shifts = {k: v for k, v in shifts.items() if k in var.dims}
variables[name] = var.shift(fill_value=fill_value_, shifts=var_shifts)
else:
variables[name] = var
return self._replace(variables)
def roll(self, shifts=None, roll_coords=None, **shifts_kwargs):
shifts = either_dict_or_kwargs(shifts, shifts_kwargs, "roll")
invalid = [k for k in shifts if k not in self.dims]
if invalid:
raise ValueError("dimensions %r do not exist" % invalid)
if roll_coords is None:
warnings.warn(
"roll_coords will be set to False in the future."
" Explicitly set roll_coords to silence warning.",
FutureWarning,
stacklevel=2,
)
roll_coords = True
unrolled_vars = () if roll_coords else self.coords
variables = {}
for k, v in self.variables.items():
if k not in unrolled_vars:
variables[k] = v.roll(
**{k: s for k, s in shifts.items() if k in v.dims}
)
else:
variables[k] = v
if roll_coords:
indexes = {}
for k, v in self.indexes.items():
(dim,) = self.variables[k].dims
if dim in shifts:
indexes[k] = roll_index(v, shifts[dim])
else:
indexes[k] = v
else:
indexes = dict(self.indexes)
return self._replace(variables, indexes=indexes)
def sortby(self, variables, ascending=True):
from .dataarray import DataArray
if not isinstance(variables, list):
variables = [variables]
else:
variables = variables
variables = [v if isinstance(v, DataArray) else self[v] for v in variables]
aligned_vars = align(self, *variables, join="left")
aligned_self = aligned_vars[0]
aligned_other_vars = aligned_vars[1:]
vars_by_dim = defaultdict(list)
for data_array in aligned_other_vars:
if data_array.ndim != 1:
raise ValueError("Input DataArray is not 1-D.")
(key,) = data_array.dims
vars_by_dim[key].append(data_array)
indices = {}
for key, arrays in vars_by_dim.items():
order = np.lexsort(tuple(reversed(arrays)))
indices[key] = order if ascending else order[::-1]
return aligned_self.isel(**indices)
def quantile(
self,
q,
dim=None,
interpolation="linear",
numeric_only=False,
keep_attrs=None,
skipna=True,
):
if isinstance(dim, str):
dims = {dim}
elif dim in [None, ...]:
dims = set(self.dims)
else:
dims = set(dim)
_assert_empty(
[d for d in dims if d not in self.dims],
"Dataset does not contain the dimensions: %s",
)
q = np.asarray(q, dtype=np.float64)
variables = {}
for name, var in self.variables.items():
reduce_dims = [d for d in var.dims if d in dims]
if reduce_dims or not var.dims:
if name not in self.coords:
if (
not numeric_only
or np.issubdtype(var.dtype, np.number)
or var.dtype == np.bool_
):
if len(reduce_dims) == var.ndim:
reduce_dims = None
variables[name] = var.quantile(
q,
dim=reduce_dims,
interpolation=interpolation,
keep_attrs=keep_attrs,
skipna=skipna,
)
else:
variables[name] = var
coord_names = {k for k in self.coords if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k in variables}
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
attrs = self.attrs if keep_attrs else None
new = self._replace_with_new_dims(
variables, coord_names=coord_names, attrs=attrs, indexes=indexes
)
return new.assign_coords(quantile=q)
def rank(self, dim, pct=False, keep_attrs=None):
if dim not in self.dims:
raise ValueError("Dataset does not contain the dimension: %s" % dim)
variables = {}
for name, var in self.variables.items():
if name in self.data_vars:
if dim in var.dims:
variables[name] = var.rank(dim, pct=pct)
else:
variables[name] = var
coord_names = set(self.coords)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
attrs = self.attrs if keep_attrs else None
return self._replace(variables, coord_names, attrs=attrs)
def differentiate(self, coord, edge_order=1, datetime_unit=None):
from .variable import Variable
if coord not in self.variables and coord not in self.dims:
raise ValueError(f"Coordinate {coord} does not exist.")
coord_var = self[coord].variable
if coord_var.ndim != 1:
raise ValueError(
"Coordinate {} must be 1 dimensional but is {}"
" dimensional".format(coord, coord_var.ndim)
)
dim = coord_var.dims[0]
if _contains_datetime_like_objects(coord_var):
if coord_var.dtype.kind in "mM" and datetime_unit is None:
datetime_unit, _ = np.datetime_data(coord_var.dtype)
elif datetime_unit is None:
datetime_unit = "s"
coord_var = coord_var._to_numeric(datetime_unit=datetime_unit)
variables = {}
for k, v in self.variables.items():
if k in self.data_vars and dim in v.dims and k not in self.coords:
if _contains_datetime_like_objects(v):
v = v._to_numeric(datetime_unit=datetime_unit)
grad = duck_array_ops.gradient(
v.data, coord_var, edge_order=edge_order, axis=v.get_axis_num(dim)
)
variables[k] = Variable(v.dims, grad)
else:
variables[k] = v
return self._replace(variables)
def integrate(
self, coord: Union[Hashable, Sequence[Hashable]], datetime_unit: str = None
) -> "Dataset":
if not isinstance(coord, (list, tuple)):
coord = (coord,)
result = self
for c in coord:
result = result._integrate_one(c, datetime_unit=datetime_unit)
return result
def _integrate_one(self, coord, datetime_unit=None):
from .variable import Variable
if coord not in self.variables and coord not in self.dims:
raise ValueError(f"Coordinate {coord} does not exist.")
coord_var = self[coord].variable
if coord_var.ndim != 1:
raise ValueError(
"Coordinate {} must be 1 dimensional but is {}"
" dimensional".format(coord, coord_var.ndim)
)
dim = coord_var.dims[0]
if _contains_datetime_like_objects(coord_var):
if coord_var.dtype.kind in "mM" and datetime_unit is None:
datetime_unit, _ = np.datetime_data(coord_var.dtype)
elif datetime_unit is None:
datetime_unit = "s"
coord_var = coord_var._replace(
data=datetime_to_numeric(coord_var.data, datetime_unit=datetime_unit)
)
variables = {}
coord_names = set()
for k, v in self.variables.items():
if k in self.coords:
if dim not in v.dims:
variables[k] = v
coord_names.add(k)
else:
if k in self.data_vars and dim in v.dims:
if _contains_datetime_like_objects(v):
v = datetime_to_numeric(v, datetime_unit=datetime_unit)
integ = duck_array_ops.trapz(
v.data, coord_var.data, axis=v.get_axis_num(dim)
)
v_dims = list(v.dims)
v_dims.remove(dim)
variables[k] = Variable(v_dims, integ)
else:
variables[k] = v
indexes = {k: v for k, v in self.indexes.items() if k in variables}
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
@property
def real(self):
return self.map(lambda x: x.real, keep_attrs=True)
@property
def imag(self):
return self.map(lambda x: x.imag, keep_attrs=True)
plot = utils.UncachedAccessor(_Dataset_PlotMethods)
def filter_by_attrs(self, **kwargs):
selection = []
for var_name, variable in self.variables.items():
has_value_flag = False
for attr_name, pattern in kwargs.items():
attr_value = variable.attrs.get(attr_name)
if (callable(pattern) and pattern(attr_value)) or attr_value == pattern:
has_value_flag = True
else:
has_value_flag = False
break
if has_value_flag is True:
selection.append(var_name)
return self[selection]
def unify_chunks(self) -> "Dataset":
try:
self.chunks
except ValueError:
pass
else:
return self.copy()
import dask.array
ds = self.copy()
dims_pos_map = {dim: index for index, dim in enumerate(ds.dims)}
dask_array_names = []
dask_unify_args = []
for name, variable in ds.variables.items():
if isinstance(variable.data, dask.array.Array):
dims_tuple = [dims_pos_map[dim] for dim in variable.dims]
dask_array_names.append(name)
dask_unify_args.append(variable.data)
dask_unify_args.append(dims_tuple)
_, rechunked_arrays = dask.array.core.unify_chunks(*dask_unify_args)
for name, new_array in zip(dask_array_names, rechunked_arrays):
ds.variables[name]._data = new_array
return ds
def map_blocks(
self,
func: "Callable[..., T_DSorDA]",
args: Sequence[Any] = (),
kwargs: Mapping[str, Any] = None,
template: Union["DataArray", "Dataset"] = None,
) -> "T_DSorDA":
from .parallel import map_blocks
return map_blocks(func, self, args, kwargs, template)
def polyfit(
self,
dim: Hashable,
deg: int,
skipna: bool = None,
rcond: float = None,
w: Union[Hashable, Any] = None,
full: bool = False,
cov: Union[bool, str] = False,
):
variables = {}
skipna_da = skipna
x = get_clean_interp_index(self, dim, strict=False)
xname = "{}_".format(self[dim].name)
order = int(deg) + 1
lhs = np.vander(x, order)
if rcond is None:
rcond = (
x.shape[0] * np.core.finfo(x.dtype).eps # type: ignore[attr-defined]
)
# Weights:
if w is not None:
if isinstance(w, Hashable):
w = self.coords[w]
w = np.asarray(w)
if w.ndim != 1:
raise TypeError("Expected a 1-d array for weights.")
if w.shape[0] != lhs.shape[0]:
raise TypeError("Expected w and {} to have the same length".format(dim))
lhs *= w[:, np.newaxis]
# Scaling
scale = np.sqrt((lhs * lhs).sum(axis=0))
lhs /= scale
degree_dim = utils.get_temp_dimname(self.dims, "degree")
rank = np.linalg.matrix_rank(lhs)
if full:
rank = xr.DataArray(rank, name=xname + "matrix_rank")
variables[rank.name] = rank
sing = np.linalg.svd(lhs, compute_uv=False)
sing = xr.DataArray(
sing,
dims=(degree_dim,),
coords={degree_dim: np.arange(rank - 1, -1, -1)},
name=xname + "singular_values",
)
variables[sing.name] = sing
for name, da in self.data_vars.items():
if dim not in da.dims:
continue
if is_duck_dask_array(da.data) and (
rank != order or full or skipna is None
):
# Current algorithm with dask and skipna=False neither supports
# deficient ranks nor does it output the "full" info (issue dask/dask#6516)
skipna_da = True
elif skipna is None:
skipna_da = bool(np.any(da.isnull()))
dims_to_stack = [dimname for dimname in da.dims if dimname != dim]
stacked_coords: Dict[Hashable, DataArray] = {}
if dims_to_stack:
stacked_dim = utils.get_temp_dimname(dims_to_stack, "stacked")
rhs = da.transpose(dim, *dims_to_stack).stack(
{stacked_dim: dims_to_stack}
)
stacked_coords = {stacked_dim: rhs[stacked_dim]}
scale_da = scale[:, np.newaxis]
else:
rhs = da
scale_da = scale
if w is not None:
rhs *= w[:, np.newaxis]
with warnings.catch_warnings():
if full: # Copy np.polyfit behavior
warnings.simplefilter("ignore", np.RankWarning)
else: # Raise only once per variable
warnings.simplefilter("once", np.RankWarning)
coeffs, residuals = duck_array_ops.least_squares(
lhs, rhs.data, rcond=rcond, skipna=skipna_da
)
if isinstance(name, str):
name = "{}_".format(name)
else:
# Thus a ReprObject => polyfit was called on a DataArray
name = ""
coeffs = xr.DataArray(
coeffs / scale_da,
dims=[degree_dim] + list(stacked_coords.keys()),
coords={degree_dim: np.arange(order)[::-1], **stacked_coords},
name=name + "polyfit_coefficients",
)
if dims_to_stack:
coeffs = coeffs.unstack(stacked_dim)
variables[coeffs.name] = coeffs
if full or (cov is True):
residuals = xr.DataArray(
residuals if dims_to_stack else residuals.squeeze(),
dims=list(stacked_coords.keys()),
coords=stacked_coords,
name=name + "polyfit_residuals",
)
if dims_to_stack:
residuals = residuals.unstack(stacked_dim)
variables[residuals.name] = residuals
if cov:
Vbase = np.linalg.inv(np.dot(lhs.T, lhs))
Vbase /= np.outer(scale, scale)
if cov == "unscaled":
fac = 1
else:
if x.shape[0] <= order:
raise ValueError(
"The number of data points must exceed order to scale the covariance matrix."
)
fac = residuals / (x.shape[0] - order)
covariance = xr.DataArray(Vbase, dims=("cov_i", "cov_j")) * fac
variables[name + "polyfit_covariance"] = covariance
return Dataset(data_vars=variables, attrs=self.attrs.copy())
def pad(
self,
pad_width: Mapping[Hashable, Union[int, Tuple[int, int]]] = None,
mode: str = "constant",
stat_length: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
constant_values: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
end_values: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
reflect_type: str = None,
**pad_width_kwargs: Any,
) -> "Dataset":
pad_width = either_dict_or_kwargs(pad_width, pad_width_kwargs, "pad")
if mode in ("edge", "reflect", "symmetric", "wrap"):
coord_pad_mode = mode
coord_pad_options = {
"stat_length": stat_length,
"constant_values": constant_values,
"end_values": end_values,
"reflect_type": reflect_type,
}
else:
coord_pad_mode = "constant"
coord_pad_options = {}
variables = {}
for name, var in self.variables.items():
var_pad_width = {k: v for k, v in pad_width.items() if k in var.dims}
if not var_pad_width:
variables[name] = var
elif name in self.data_vars:
variables[name] = var.pad(
pad_width=var_pad_width,
mode=mode,
stat_length=stat_length,
constant_values=constant_values,
end_values=end_values,
reflect_type=reflect_type,
)
else:
variables[name] = var.pad(
pad_width=var_pad_width,
mode=coord_pad_mode,
**coord_pad_options, # type: ignore[arg-type]
)
return self._replace_vars_and_dims(variables)
def idxmin(
self,
dim: Hashable = None,
skipna: bool = None,
fill_value: Any = dtypes.NA,
keep_attrs: bool = None,
) -> "Dataset":
return self.map(
methodcaller(
"idxmin",
dim=dim,
skipna=skipna,
fill_value=fill_value,
keep_attrs=keep_attrs,
)
)
def idxmax(
self,
dim: Hashable = None,
skipna: bool = None,
fill_value: Any = dtypes.NA,
keep_attrs: bool = None,
) -> "Dataset":
return self.map(
methodcaller(
"idxmax",
dim=dim,
skipna=skipna,
fill_value=fill_value,
keep_attrs=keep_attrs,
)
)
def argmin(self, dim=None, **kwargs):
if dim is None:
warnings.warn(
"Once the behaviour of DataArray.argmin() and Variable.argmin() without "
"dim changes to return a dict of indices of each dimension, for "
"consistency it will be an error to call Dataset.argmin() with no argument,"
"since we don't return a dict of Datasets.",
DeprecationWarning,
stacklevel=2,
)
if (
dim is None
or (not isinstance(dim, Sequence) and dim is not ...)
or isinstance(dim, str)
):
argmin_func = getattr(duck_array_ops, "argmin")
return self.reduce(argmin_func, dim=dim, **kwargs)
else:
raise ValueError(
"When dim is a sequence or ..., DataArray.argmin() returns a dict. "
"dicts cannot be contained in a Dataset, so cannot call "
"Dataset.argmin() with a sequence or ... for dim"
)
def argmax(self, dim=None, **kwargs):
if dim is None:
warnings.warn(
"Once the behaviour of DataArray.argmin() and Variable.argmin() without "
"dim changes to return a dict of indices of each dimension, for "
"consistency it will be an error to call Dataset.argmin() with no argument,"
"since we don't return a dict of Datasets.",
DeprecationWarning,
stacklevel=2,
)
if (
dim is None
or (not isinstance(dim, Sequence) and dim is not ...)
or isinstance(dim, str)
):
# Return int index if single dimension is passed, and is not part of a
# sequence
argmax_func = getattr(duck_array_ops, "argmax")
return self.reduce(argmax_func, dim=dim, **kwargs)
else:
raise ValueError(
"When dim is a sequence or ..., DataArray.argmin() returns a dict. "
"dicts cannot be contained in a Dataset, so cannot call "
"Dataset.argmin() with a sequence or ... for dim"
)
def query(
self,
queries: Mapping[Hashable, Any] = None,
parser: str = "pandas",
engine: str = None,
missing_dims: str = "raise",
**queries_kwargs: Any,
) -> "Dataset":
# allow queries to be given either as a dict or as kwargs
queries = either_dict_or_kwargs(queries, queries_kwargs, "query")
# check queries
for dim, expr in queries.items():
if not isinstance(expr, str):
msg = f"expr for dim {dim} must be a string to be evaluated, {type(expr)} given"
raise ValueError(msg)
# evaluate the queries to create the indexers
indexers = {
dim: pd.eval(expr, resolvers=[self], parser=parser, engine=engine)
for dim, expr in queries.items()
}
# apply the selection
return self.isel(indexers, missing_dims=missing_dims)
def curvefit(
self,
coords: Union[Union[str, "DataArray"], Iterable[Union[str, "DataArray"]]],
func: Callable[..., Any],
reduce_dims: Union[Hashable, Iterable[Hashable]] = None,
skipna: bool = True,
p0: Dict[str, Any] = None,
bounds: Dict[str, Any] = None,
param_names: Sequence[str] = None,
kwargs: Dict[str, Any] = None,
):
from scipy.optimize import curve_fit
if p0 is None:
p0 = {}
if bounds is None:
bounds = {}
if kwargs is None:
kwargs = {}
if not reduce_dims:
reduce_dims_ = []
elif isinstance(reduce_dims, str) or not isinstance(reduce_dims, Iterable):
reduce_dims_ = [reduce_dims]
else:
reduce_dims_ = list(reduce_dims)
if (
isinstance(coords, str)
or isinstance(coords, xr.DataArray)
or not isinstance(coords, Iterable)
):
coords = [coords]
coords_ = [self[coord] if isinstance(coord, str) else coord for coord in coords]
# Determine whether any coords are dims on self
for coord in coords_:
reduce_dims_ += [c for c in self.dims if coord.equals(self[c])]
reduce_dims_ = list(set(reduce_dims_))
preserved_dims = list(set(self.dims) - set(reduce_dims_))
if not reduce_dims_:
raise ValueError(
"No arguments to `coords` were identified as a dimension on the calling "
"object, and no dims were supplied to `reduce_dims`. This would result "
"in fitting on scalar data."
)
# Broadcast all coords with each other
coords_ = xr.broadcast(*coords_)
coords_ = [
coord.broadcast_like(self, exclude=preserved_dims) for coord in coords_
]
params, func_args = _get_func_args(func, param_names)
param_defaults, bounds_defaults = _initialize_curvefit_params(
params, p0, bounds, func_args
)
n_params = len(params)
kwargs.setdefault("p0", [param_defaults[p] for p in params])
kwargs.setdefault(
"bounds",
[
[bounds_defaults[p][0] for p in params],
[bounds_defaults[p][1] for p in params],
],
)
def _wrapper(Y, *coords_, **kwargs):
# Wrap curve_fit with raveled coordinates and pointwise NaN handling
x = np.vstack([c.ravel() for c in coords_])
y = Y.ravel()
if skipna:
mask = np.all([np.any(~np.isnan(x), axis=0), ~np.isnan(y)], axis=0)
x = x[:, mask]
y = y[mask]
if not len(y):
popt = np.full([n_params], np.nan)
pcov = np.full([n_params, n_params], np.nan)
return popt, pcov
x = np.squeeze(x)
popt, pcov = curve_fit(func, x, y, **kwargs)
return popt, pcov
result = xr.Dataset()
for name, da in self.data_vars.items():
if name is xr.core.dataarray._THIS_ARRAY:
name = ""
else:
name = f"{str(name)}_"
popt, pcov = xr.apply_ufunc(
_wrapper,
da,
*coords_,
vectorize=True,
dask="parallelized",
input_core_dims=[reduce_dims_ for d in range(len(coords_) + 1)],
output_core_dims=[["param"], ["cov_i", "cov_j"]],
dask_gufunc_kwargs={
"output_sizes": {
"param": n_params,
"cov_i": n_params,
"cov_j": n_params,
},
},
output_dtypes=(np.float64, np.float64),
exclude_dims=set(reduce_dims_),
kwargs=kwargs,
)
result[name + "curvefit_coefficients"] = popt
result[name + "curvefit_covariance"] = pcov
result = result.assign_coords(
{"param": params, "cov_i": params, "cov_j": params}
)
result.attrs = self.attrs.copy()
return result
ops.inject_all_ops_and_reduce_methods(Dataset, array_only=False)
| true | true |
f72c3934b0697c32c252b1d2e817e435900da1e3 | 441 | py | Python | metaci/plan/migrations/0018_planrepository_active.py | sfdc-qbranch/MetaCI | 78ac0d2bccd2db381998321ebd71029dd5d9ab39 | [
"BSD-3-Clause"
] | 48 | 2018-10-24T14:52:06.000Z | 2022-03-25T21:14:50.000Z | metaci/plan/migrations/0018_planrepository_active.py | sfdc-qbranch/MetaCI | 78ac0d2bccd2db381998321ebd71029dd5d9ab39 | [
"BSD-3-Clause"
] | 2,034 | 2018-10-31T20:59:16.000Z | 2022-03-22T21:38:03.000Z | metaci/plan/migrations/0018_planrepository_active.py | sfdc-qbranch/MetaCI | 78ac0d2bccd2db381998321ebd71029dd5d9ab39 | [
"BSD-3-Clause"
] | 27 | 2018-12-24T18:16:23.000Z | 2021-12-15T17:57:27.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-09-13 23:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("plan", "0016_auto_20180904_1457")]
operations = [
migrations.AddField(
model_name="planrepository",
name="active",
field=models.BooleanField(default=True),
)
]
| 23.210526 | 56 | 0.643991 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("plan", "0016_auto_20180904_1457")]
operations = [
migrations.AddField(
model_name="planrepository",
name="active",
field=models.BooleanField(default=True),
)
]
| true | true |
f72c39bc796a19aeb0f55dc3bee1129236c8a00e | 111,695 | py | Python | salt/grains/core.py | MeAndTheFirefly/salt | 77fc3ec3ee25c1b769cc66ddee09067d18080844 | [
"Apache-2.0"
] | 2 | 2016-11-14T15:08:53.000Z | 2016-11-20T09:25:30.000Z | salt/grains/core.py | MeAndTheFirefly/salt | 77fc3ec3ee25c1b769cc66ddee09067d18080844 | [
"Apache-2.0"
] | 3 | 2021-03-31T19:53:24.000Z | 2021-12-13T20:46:19.000Z | salt/grains/core.py | MeAndTheFirefly/salt | 77fc3ec3ee25c1b769cc66ddee09067d18080844 | [
"Apache-2.0"
] | 2 | 2020-11-04T06:32:02.000Z | 2020-11-06T11:01:18.000Z | # -*- coding: utf-8 -*-
"""
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
"""
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import hashlib
import locale
import logging
import os
import platform
import re
import socket
import sys
import time
import uuid
from errno import EACCES, EPERM
import distro
import salt.exceptions
import salt.log
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.network
import salt.modules.smbios
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
from salt.utils.network import _get_interfaces
# rewrite distro.linux_distribution to allow best=True kwarg in version(), needed to get the minor version numbers in CentOS
def _linux_distribution():
return (
distro.id(),
distro.version(best=True),
distro.codename(),
)
try:
import dateutil.tz # pylint: disable=import-error
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
"Unable to import Python wmi module, some core grains " "will be missing"
)
__proxyenabled__ = ["*"]
__FQDN__ = None
__salt__ = {
"cmd.run": salt.modules.cmdmod._run_quiet,
"cmd.retcode": salt.modules.cmdmod._retcode_quiet,
"cmd.run_all": salt.modules.cmdmod._run_all_quiet,
"smbios.records": salt.modules.smbios.records,
"smbios.get": salt.modules.smbios.get,
"network.fqdns": salt.modules.network.fqdns,
}
HAS_UNAME = hasattr(os, "uname")
# Possible value for h_errno defined in netdb.h
HOST_NOT_FOUND = 1
NO_DATA = 4
def _windows_cpudata():
"""
Return some CPU information on Windows minions
"""
# Provides:
# num_cpus
# cpu_model
grains = {}
if "NUMBER_OF_PROCESSORS" in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains["num_cpus"] = int(os.environ["NUMBER_OF_PROCESSORS"])
except ValueError:
grains["num_cpus"] = 1
grains["cpu_model"] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString",
).get("vdata")
return grains
def _linux_cpudata():
"""
Return some CPU information for Linux minions
"""
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = "/proc/cpuinfo"
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, "r") as _fp:
for line in _fp:
comps = line.split(":")
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == "processor":
grains["num_cpus"] = int(val) + 1
# head -2 /proc/cpuinfo
# vendor_id : IBM/S390
# # processors : 2
elif key == "# processors":
grains["num_cpus"] = int(val)
elif key == "vendor_id":
grains["cpu_model"] = val
elif key == "model name":
grains["cpu_model"] = val
elif key == "flags":
grains["cpu_flags"] = val.split()
elif key == "Features":
grains["cpu_flags"] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == "Processor":
grains["cpu_model"] = val.split("-")[0]
grains["num_cpus"] = 1
if "num_cpus" not in grains:
grains["num_cpus"] = 0
if "cpu_model" not in grains:
grains["cpu_model"] = "Unknown"
if "cpu_flags" not in grains:
grains["cpu_flags"] = []
return grains
def _linux_gpu_data():
"""
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
"""
if __opts__.get("enable_lspci", True) is False:
return {}
if __opts__.get("enable_gpu_grains", True) is False:
return {}
lspci = salt.utils.path.which("lspci")
if not lspci:
log.debug(
"The `lspci` binary is not available on the system. GPU grains "
"will not be available."
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = [
"nvidia",
"amd",
"ati",
"intel",
"cirrus logic",
"vmware",
"matrox",
"aspeed",
]
gpu_classes = ("vga compatible controller", "3d controller", "display controller")
devs = []
try:
lspci_out = __salt__["cmd.run"]("{0} -vmm".format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append("")
for line in lspci_list:
# check for record-separating empty lines
if line == "":
if cur_dev.get("Class", "").lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r"^\w+:\s+.*", line):
key, val = line.split(":", 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug("Unexpected lspci output: '%s'", line)
if error:
log.warning(
"Error loading grains, unexpected linux_gpu_data output, "
"check that you have a valid shell configured and "
"permissions to run lspci command"
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split("[^A-Za-z0-9]", gpu["Vendor"].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = "unknown"
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({"vendor": vendor, "model": gpu["Device"]})
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _netbsd_gpu_data():
"""
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
"""
known_vendors = [
"nvidia",
"amd",
"ati",
"intel",
"cirrus logic",
"vmware",
"matrox",
"aspeed",
]
gpus = []
try:
pcictl_out = __salt__["cmd.run"]("pcictl pci0 list")
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r"[0-9:]+ ({0}) (.+) \(VGA .+\)".format(vendor), line, re.IGNORECASE
)
if vendor_match:
gpus.append(
{
"vendor": vendor_match.group(1),
"model": vendor_match.group(2),
}
)
except OSError:
pass
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _osx_gpudata():
"""
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
"""
gpus = []
try:
pcictl_out = __salt__["cmd.run"]("system_profiler SPDisplaysDataType")
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(": ")
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(" ")
vendor = vendor.lower()
gpus.append({"vendor": vendor, "model": model})
except OSError:
pass
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _bsd_cpudata(osdata):
"""
Return CPU information for BSD-like systems
"""
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which("sysctl")
arch = salt.utils.path.which("arch")
cmds = {}
if sysctl:
cmds.update(
{
"num_cpus": "{0} -n hw.ncpu".format(sysctl),
"cpuarch": "{0} -n hw.machine".format(sysctl),
"cpu_model": "{0} -n hw.model".format(sysctl),
}
)
if arch and osdata["kernel"] == "OpenBSD":
cmds["cpuarch"] = "{0} -s".format(arch)
if osdata["kernel"] == "Darwin":
cmds["cpu_model"] = "{0} -n machdep.cpu.brand_string".format(sysctl)
cmds["cpu_flags"] = "{0} -n machdep.cpu.features".format(sysctl)
grains = dict([(k, __salt__["cmd.run"](v)) for k, v in six.iteritems(cmds)])
if "cpu_flags" in grains and isinstance(grains["cpu_flags"], six.string_types):
grains["cpu_flags"] = grains["cpu_flags"].split(" ")
if osdata["kernel"] == "NetBSD":
grains["cpu_flags"] = []
for line in __salt__["cmd.run"]("cpuctl identify 0").splitlines():
cpu_match = re.match(r"cpu[0-9]:\ features[0-9]?\ .+<(.+)>", line)
if cpu_match:
flag = cpu_match.group(1).split(",")
grains["cpu_flags"].extend(flag)
if osdata["kernel"] == "FreeBSD" and os.path.isfile("/var/run/dmesg.boot"):
grains["cpu_flags"] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen("/var/run/dmesg.boot", "r") as _fp:
cpu_here = False
for line in _fp:
if line.startswith("CPU: "):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(" "):
break # game over
if "Features" in line:
start = line.find("<")
end = line.find(">")
if start > 0 and end > 0:
flag = line[start + 1 : end].split(",")
grains["cpu_flags"].extend(flag)
try:
grains["num_cpus"] = int(grains["num_cpus"])
except ValueError:
grains["num_cpus"] = 1
return grains
def _sunos_cpudata():
"""
Return the CPU information for Solaris-like systems
"""
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains["cpu_flags"] = []
grains["cpuarch"] = __salt__["cmd.run"]("isainfo -k")
psrinfo = "/usr/sbin/psrinfo 2>/dev/null"
grains["num_cpus"] = len(
__salt__["cmd.run"](psrinfo, python_shell=True).splitlines()
)
kstat_info = "kstat -p cpu_info:*:*:brand"
for line in __salt__["cmd.run"](kstat_info).splitlines():
match = re.match(r"(\w+:\d+:\w+\d+:\w+)\s+(.+)", line)
if match:
grains["cpu_model"] = match.group(2)
isainfo = "isainfo -n -v"
for line in __salt__["cmd.run"](isainfo).splitlines():
match = re.match(r"^\s+(.+)", line)
if match:
cpu_flags = match.group(1).split()
grains["cpu_flags"].extend(cpu_flags)
return grains
def _aix_cpudata():
"""
Return CPU information for AIX systems
"""
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which("prtconf")
if cmd:
data = __salt__["cmd.run"]("{0}".format(cmd)) + os.linesep
for dest, regstring in (
("cpuarch", r"(?im)^\s*Processor\s+Type:\s+(\S+)"),
("cpu_flags", r"(?im)^\s*Processor\s+Version:\s+(\S+)"),
("cpu_model", r"(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)"),
("num_cpus", r"(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)"),
):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", "")
else:
log.error("The 'prtconf' binary was not found in $PATH.")
return grains
def _linux_memdata():
"""
Return the memory information for Linux-like systems
"""
grains = {"mem_total": 0, "swap_total": 0}
meminfo = "/proc/meminfo"
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, "r") as ifile:
for line in ifile:
comps = line.rstrip("\n").split(":")
if not len(comps) > 1:
continue
if comps[0].strip() == "MemTotal":
# Use floor division to force output to be an integer
grains["mem_total"] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == "SwapTotal":
# Use floor division to force output to be an integer
grains["swap_total"] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
"""
Return the memory information for BSD-like systems
"""
grains = {"mem_total": 0, "swap_total": 0}
sysctl = salt.utils.path.which("sysctl")
if sysctl:
mem = __salt__["cmd.run"]("{0} -n hw.memsize".format(sysctl))
swap_total = (
__salt__["cmd.run"]("{0} -n vm.swapusage".format(sysctl))
.split()[2]
.replace(",", ".")
)
if swap_total.endswith("K"):
_power = 2 ** 10
elif swap_total.endswith("M"):
_power = 2 ** 20
elif swap_total.endswith("G"):
_power = 2 ** 30
swap_total = float(swap_total[:-1]) * _power
grains["mem_total"] = int(mem) // 1024 // 1024
grains["swap_total"] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
"""
Return the memory information for BSD-like systems
"""
grains = {"mem_total": 0, "swap_total": 0}
sysctl = salt.utils.path.which("sysctl")
if sysctl:
mem = __salt__["cmd.run"]("{0} -n hw.physmem".format(sysctl))
if osdata["kernel"] == "NetBSD" and mem.startswith("-"):
mem = __salt__["cmd.run"]("{0} -n hw.physmem64".format(sysctl))
grains["mem_total"] = int(mem) // 1024 // 1024
if osdata["kernel"] in ["OpenBSD", "NetBSD"]:
swapctl = salt.utils.path.which("swapctl")
swap_data = __salt__["cmd.run"]("{0} -sk".format(swapctl))
if swap_data == "no swap devices configured":
swap_total = 0
else:
swap_total = swap_data.split(" ")[1]
else:
swap_total = __salt__["cmd.run"]("{0} -n vm.swap_total".format(sysctl))
grains["swap_total"] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
"""
Return the memory information for SunOS-like systems
"""
grains = {"mem_total": 0, "swap_total": 0}
prtconf = "/usr/sbin/prtconf 2>/dev/null"
for line in __salt__["cmd.run"](prtconf, python_shell=True).splitlines():
comps = line.split(" ")
if comps[0].strip() == "Memory" and comps[1].strip() == "size:":
grains["mem_total"] = int(comps[2].strip())
swap_cmd = salt.utils.path.which("swap")
swap_data = __salt__["cmd.run"]("{0} -s".format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains["swap_total"] = swap_total
return grains
def _aix_memdata():
"""
Return the memory information for AIX systems
"""
grains = {"mem_total": 0, "swap_total": 0}
prtconf = salt.utils.path.which("prtconf")
if prtconf:
for line in __salt__["cmd.run"](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(" ") if x]
if len(comps) > 2 and "Memory" in comps[0] and "Size" in comps[1]:
grains["mem_total"] = int(comps[2])
break
else:
log.error("The 'prtconf' binary was not found in $PATH.")
swap_cmd = salt.utils.path.which("swap")
if swap_cmd:
swap_data = __salt__["cmd.run"]("{0} -s".format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains["swap_total"] = swap_total
else:
log.error("The 'swap' binary was not found in $PATH.")
return grains
def _windows_memdata():
"""
Return the memory information for Windows systems
"""
grains = {"mem_total": 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()["TotalPhys"]
# return memory info in gigabytes
grains["mem_total"] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
"""
Gather information about the system memory
"""
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {"mem_total": 0}
if osdata["kernel"] == "Linux":
grains.update(_linux_memdata())
elif osdata["kernel"] in ("FreeBSD", "OpenBSD", "NetBSD"):
grains.update(_bsd_memdata(osdata))
elif osdata["kernel"] == "Darwin":
grains.update(_osx_memdata())
elif osdata["kernel"] == "SunOS":
grains.update(_sunos_memdata())
elif osdata["kernel"] == "AIX":
grains.update(_aix_memdata())
elif osdata["kernel"] == "Windows" and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
"""
Parse the output of lsattr -El sys0 for os_uuid
"""
grains = {}
cmd = salt.utils.path.which("lsattr")
if cmd:
data = __salt__["cmd.run"]("{0} -El sys0".format(cmd)) + os.linesep
uuid_regexes = [re.compile(r"(?im)^\s*os_uuid\s+(\S+)\s+(.*)")]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["machine_id"] = res.group(1).strip()
break
else:
log.error("The 'lsattr' binary was not found in $PATH.")
return grains
def _windows_virtual(osdata):
"""
Returns what type of virtual hardware is under the hood, kvm or physical
"""
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata["kernel"] != "Windows":
return grains
grains["virtual"] = osdata.get("virtual", "physical")
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get("manufacturer", "")
if manufacturer is None:
manufacturer = ""
productname = osdata.get("productname", "")
if productname is None:
productname = ""
if "QEMU" in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains["virtual"] = "kvm"
if "Bochs" in manufacturer:
grains["virtual"] = "kvm"
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif "oVirt" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "oVirt"
# Red Hat Enterprise Virtualization
elif "RHEV Hypervisor" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
# Product Name: VirtualBox
elif "VirtualBox" in productname:
grains["virtual"] = "VirtualBox"
# Product Name: VMware Virtual Platform
elif "VMware Virtual Platform" in productname:
grains["virtual"] = "VMware"
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif "Microsoft" in manufacturer and "Virtual Machine" in productname:
grains["virtual"] = "VirtualPC"
# Manufacturer: Parallels Software International Inc.
elif "Parallels Software" in manufacturer:
grains["virtual"] = "Parallels"
# Apache CloudStack
elif "CloudStack KVM Hypervisor" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "cloudstack"
return grains
def _virtual(osdata):
"""
Returns what type of virtual hardware is under the hood, kvm or physical
"""
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {"virtual": osdata.get("virtual", "physical")}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ("AIX",)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ["systemd-detect-virt", "virt-what", "dmidecode"]
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata["kernel"] not in skip_cmds:
if salt.utils.path.which("virt-what"):
_cmds = ["virt-what"]
# Check if enable_lspci is True or False
if __opts__.get("enable_lspci", True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists("/proc/bus/pci"):
_cmds += ["lspci"]
# Add additional last resort commands
if osdata["kernel"] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if (
HAS_UNAME
and osdata["kernel"] == "Linux"
and "BrandZ virtual linux" in os.uname()
):
grains["virtual"] = "zone"
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata["kernel"] == "Darwin":
command = "system_profiler"
args = ["SPDisplaysDataType"]
elif osdata["kernel"] == "SunOS":
virtinfo = salt.utils.path.which("virtinfo")
if virtinfo:
try:
ret = __salt__["cmd.run_all"](virtinfo)
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret["stdout"].endswith("not supported"):
command = "prtdiag"
else:
command = "virtinfo"
args.append("-c current list -H -o name")
else:
command = "prtdiag"
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = "{0} {1}".format(cmd, " ".join(args))
try:
ret = __salt__["cmd.run_all"](cmd)
if ret["retcode"] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if (
salt.utils.platform.is_windows()
or "systemd-detect-virt" in cmd
or "prtdiag" in cmd
):
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret["stdout"]
if command == "system_profiler":
macoutput = output.lower()
if "0x1ab8" in macoutput:
grains["virtual"] = "Parallels"
if "parallels" in macoutput:
grains["virtual"] = "Parallels"
if "vmware" in macoutput:
grains["virtual"] = "VMware"
if "0x15ad" in macoutput:
grains["virtual"] = "VMware"
if "virtualbox" in macoutput:
grains["virtual"] = "VirtualBox"
# Break out of the loop so the next log message is not issued
break
elif command == "systemd-detect-virt":
if output in (
"qemu",
"kvm",
"oracle",
"xen",
"bochs",
"chroot",
"uml",
"systemd-nspawn",
):
grains["virtual"] = output
break
elif "vmware" in output:
grains["virtual"] = "VMware"
break
elif "microsoft" in output:
grains["virtual"] = "VirtualPC"
break
elif "lxc" in output:
grains["virtual"] = "LXC"
break
elif "systemd-nspawn" in output:
grains["virtual"] = "LXC"
break
elif command == "virt-what":
for line in output.splitlines():
if line in ("kvm", "qemu", "uml", "xen", "lxc"):
grains["virtual"] = line
break
elif "vmware" in line:
grains["virtual"] = "VMware"
break
elif "parallels" in line:
grains["virtual"] = "Parallels"
break
elif "hyperv" in line:
grains["virtual"] = "HyperV"
break
elif command == "dmidecode":
# Product Name: VirtualBox
if "Vendor: QEMU" in output:
# FIXME: Make this detect between kvm or qemu
grains["virtual"] = "kvm"
if "Manufacturer: QEMU" in output:
grains["virtual"] = "kvm"
if "Vendor: Bochs" in output:
grains["virtual"] = "kvm"
if "Manufacturer: Bochs" in output:
grains["virtual"] = "kvm"
if "BHYVE" in output:
grains["virtual"] = "bhyve"
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif "Manufacturer: oVirt" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "ovirt"
# Red Hat Enterprise Virtualization
elif "Product Name: RHEV Hypervisor" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
elif "VirtualBox" in output:
grains["virtual"] = "VirtualBox"
# Product Name: VMware Virtual Platform
elif "VMware" in output:
grains["virtual"] = "VMware"
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ": Microsoft" in output and "Virtual Machine" in output:
grains["virtual"] = "VirtualPC"
# Manufacturer: Parallels Software International Inc.
elif "Parallels Software" in output:
grains["virtual"] = "Parallels"
elif "Manufacturer: Google" in output:
grains["virtual"] = "kvm"
# Proxmox KVM
elif "Vendor: SeaBIOS" in output:
grains["virtual"] = "kvm"
# Break out of the loop, lspci parsing is not necessary
break
elif command == "lspci":
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if "vmware" in model:
grains["virtual"] = "VMware"
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif "virtualbox" in model:
grains["virtual"] = "VirtualBox"
elif "qemu" in model:
grains["virtual"] = "kvm"
elif "virtio" in model:
grains["virtual"] = "kvm"
# Break out of the loop so the next log message is not issued
break
elif command == "prtdiag":
model = output.lower().split("\n")[0]
if "vmware" in model:
grains["virtual"] = "VMware"
elif "virtualbox" in model:
grains["virtual"] = "VirtualBox"
elif "qemu" in model:
grains["virtual"] = "kvm"
elif "joyent smartdc hvm" in model:
grains["virtual"] = "kvm"
break
elif command == "virtinfo":
if output == "logical-domain":
grains["virtual"] = "LDOM"
roles = []
for role in ("control", "io", "root", "service"):
subtype_cmd = "{0} -c current get -H -o value {1}-role".format(
command, role
)
ret = __salt__["cmd.run"]("{0}".format(subtype_cmd))
if ret == "true":
roles.append(role)
if roles:
grains["virtual_subtype"] = roles
elif output == "non-global-zone":
grains["virtual"] = "zone"
grains["virtual_subtype"] = "non-global"
elif output == "kernel-zone":
grains["virtual"] = "zone"
grains["virtual_subtype"] = "kernel"
elif output == "vmware":
grains["virtual"] = "VMware"
break
choices = ("Linux", "HP-UX")
isdir = os.path.isdir
sysctl = salt.utils.path.which("sysctl")
if osdata["kernel"] in choices:
if os.path.isdir("/proc"):
try:
self_root = os.stat("/")
init_root = os.stat("/proc/1/root/.")
if self_root != init_root:
grains["virtual_subtype"] = "chroot"
except (IOError, OSError):
pass
if isdir("/proc/vz"):
if os.path.isfile("/proc/vz/version"):
grains["virtual"] = "openvzhn"
elif os.path.isfile("/proc/vz/veinfo"):
grains["virtual"] = "openvzve"
# a posteriori, it's expected for these to have failed:
failed_commands.discard("lspci")
failed_commands.discard("dmidecode")
# Provide additional detection for OpenVZ
if os.path.isfile("/proc/self/status"):
with salt.utils.files.fopen("/proc/self/status") as status_file:
vz_re = re.compile(r"^envID:\s+(\d+)$")
for line in status_file:
vz_match = vz_re.match(line.rstrip("\n"))
if vz_match and int(vz_match.groups()[0]) != 0:
grains["virtual"] = "openvzve"
elif vz_match and int(vz_match.groups()[0]) == 0:
grains["virtual"] = "openvzhn"
if isdir("/proc/sys/xen") or isdir("/sys/bus/xen") or isdir("/proc/xen"):
if os.path.isfile("/proc/xen/xsd_kva"):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains["virtual_subtype"] = "Xen Dom0"
else:
if osdata.get("productname", "") == "HVM domU":
# Requires dmidecode!
grains["virtual_subtype"] = "Xen HVM DomU"
elif os.path.isfile("/proc/xen/capabilities") and os.access(
"/proc/xen/capabilities", os.R_OK
):
with salt.utils.files.fopen("/proc/xen/capabilities") as fhr:
if "control_d" not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains["virtual_subtype"] = "Xen PV DomU"
else:
# Shouldn't get to this, but just in case
grains["virtual_subtype"] = "Xen Dom0"
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir("/sys/bus/xen"):
if "xen:" in __salt__["cmd.run"]("dmesg").lower():
grains["virtual_subtype"] = "Xen PV DomU"
elif os.path.isfile("/sys/bus/xen/drivers/xenconsole"):
# An actual DomU will have the xenconsole driver
grains["virtual_subtype"] = "Xen PV DomU"
# If a Dom0 or DomU was detected, obviously this is xen
if "dom" in grains.get("virtual_subtype", "").lower():
grains["virtual"] = "xen"
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile("/proc/1/cgroup"):
try:
with salt.utils.files.fopen("/proc/1/cgroup", "r") as fhr:
fhr_contents = fhr.read()
if ":/lxc/" in fhr_contents:
grains["virtual"] = "container"
grains["virtual_subtype"] = "LXC"
elif ":/kubepods/" in fhr_contents:
grains["virtual_subtype"] = "kubernetes"
elif ":/libpod_parent/" in fhr_contents:
grains["virtual_subtype"] = "libpod"
else:
if any(
x in fhr_contents
for x in (":/system.slice/docker", ":/docker/", ":/docker-ce/")
):
grains["virtual"] = "container"
grains["virtual_subtype"] = "Docker"
except IOError:
pass
if os.path.isfile("/proc/cpuinfo"):
with salt.utils.files.fopen("/proc/cpuinfo", "r") as fhr:
if "QEMU Virtual CPU" in fhr.read():
grains["virtual"] = "kvm"
if os.path.isfile("/sys/devices/virtual/dmi/id/product_name"):
try:
with salt.utils.files.fopen(
"/sys/devices/virtual/dmi/id/product_name", "r"
) as fhr:
output = salt.utils.stringutils.to_unicode(
fhr.read(), errors="replace"
)
if "VirtualBox" in output:
grains["virtual"] = "VirtualBox"
elif "RHEV Hypervisor" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
elif "oVirt Node" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "ovirt"
elif "Google" in output:
grains["virtual"] = "gce"
elif "BHYVE" in output:
grains["virtual"] = "bhyve"
except UnicodeDecodeError:
# Some firmwares provide non-valid 'product_name'
# files, ignore them
log.debug(
"The content in /sys/devices/virtual/dmi/id/product_name is not valid"
)
except IOError:
pass
elif osdata["kernel"] == "FreeBSD":
kenv = salt.utils.path.which("kenv")
if kenv:
product = __salt__["cmd.run"]("{0} smbios.system.product".format(kenv))
maker = __salt__["cmd.run"]("{0} smbios.system.maker".format(kenv))
if product.startswith("VMware"):
grains["virtual"] = "VMware"
if product.startswith("VirtualBox"):
grains["virtual"] = "VirtualBox"
if maker.startswith("Xen"):
grains["virtual_subtype"] = "{0} {1}".format(maker, product)
grains["virtual"] = "xen"
if maker.startswith("Microsoft") and product.startswith("Virtual"):
grains["virtual"] = "VirtualPC"
if maker.startswith("OpenStack"):
grains["virtual"] = "OpenStack"
if maker.startswith("Bochs"):
grains["virtual"] = "kvm"
if sysctl:
hv_vendor = __salt__["cmd.run"]("{0} -n hw.hv_vendor".format(sysctl))
model = __salt__["cmd.run"]("{0} -n hw.model".format(sysctl))
jail = __salt__["cmd.run"]("{0} -n security.jail.jailed".format(sysctl))
if "bhyve" in hv_vendor:
grains["virtual"] = "bhyve"
elif "QEMU Virtual CPU" in model:
grains["virtual"] = "kvm"
if jail == "1":
grains["virtual_subtype"] = "jail"
elif osdata["kernel"] == "OpenBSD":
if "manufacturer" in osdata:
if osdata["manufacturer"] in ["QEMU", "Red Hat", "Joyent"]:
grains["virtual"] = "kvm"
if osdata["manufacturer"] == "OpenBSD":
grains["virtual"] = "vmm"
elif osdata["kernel"] == "NetBSD":
if sysctl:
if "QEMU Virtual CPU" in __salt__["cmd.run"](
"{0} -n machdep.cpu_brand".format(sysctl)
):
grains["virtual"] = "kvm"
elif "invalid" not in __salt__["cmd.run"](
"{0} -n machdep.xen.suspend".format(sysctl)
):
grains["virtual"] = "Xen PV DomU"
elif "VMware" in __salt__["cmd.run"](
"{0} -n machdep.dmi.system-vendor".format(sysctl)
):
grains["virtual"] = "VMware"
# NetBSD has Xen dom0 support
elif (
__salt__["cmd.run"]("{0} -n machdep.idle-mechanism".format(sysctl))
== "xen"
):
if os.path.isfile("/var/run/xenconsoled.pid"):
grains["virtual_subtype"] = "Xen Dom0"
elif osdata["kernel"] == "SunOS":
# we did not get any data from virtinfo or prtdiag
# check the zonename here as fallback
zonename = salt.utils.path.which("zonename")
if zonename:
zone = __salt__["cmd.run"]("{0}".format(zonename))
if zone != "global":
grains["virtual"] = "zone"
# last ditch efford to check the brand identifier
elif os.path.isdir("/.SUNWnative"):
grains["virtual"] = "zone"
# If we have a virtual_subtype, we're virtual, but maybe we couldn't
# figure out what specific virtual type we were?
if grains.get("virtual_subtype") and grains["virtual"] == "physical":
grains["virtual"] = "virtual"
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
"cannot execute it. Grains output might not be "
"accurate.",
command,
)
return grains
def _virtual_hv(osdata):
"""
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
"""
grains = {}
# Bail early if we're not running on Xen
try:
if "xen" not in osdata["virtual"]:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ("major", "minor", "extra"):
with salt.utils.files.fopen(
"/sys/hypervisor/version/{}".format(fn), "r"
) as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains["virtual_hv_version"] = "{}.{}{}".format(
version["major"], version["minor"], version["extra"]
)
grains["virtual_hv_version_info"] = [
version["major"],
version["minor"],
version["extra"],
]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {
0: "writable_page_tables",
1: "writable_descriptor_tables",
2: "auto_translated_physmap",
3: "supervisor_mode_kernel",
4: "pae_pgdir_above_4gb",
5: "mmu_pt_update_preserve_ad",
7: "gnttab_map_avail_bits",
8: "hvm_callback_vector",
9: "hvm_safe_pvclock",
10: "hvm_pirqs",
11: "dom0",
12: "grant_map_identity",
13: "memory_op_vnode_supported",
14: "ARM_SMCCC_supported",
}
try:
with salt.utils.files.fopen("/sys/hypervisor/properties/features", "r") as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains["virtual_hv_features"] = features
grains["virtual_hv_features_list"] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
"""
Return the ps grain
"""
grains = {}
bsd_choices = ("FreeBSD", "NetBSD", "OpenBSD", "MacOS")
if osdata["os"] in bsd_choices:
grains["ps"] = "ps auxwww"
elif osdata["os_family"] == "Solaris":
grains["ps"] = "/usr/ucb/ps auxwww"
elif osdata["os"] == "Windows":
grains["ps"] = "tasklist.exe"
elif osdata.get("virtual", "") == "openvzhn":
grains["ps"] = (
'ps -fH -p $(grep -l "^envID:[[:space:]]*0\\$" '
'/proc/[0-9]*/status | sed -e "s=/proc/\\([0-9]*\\)/.*=\\1=") '
"| awk '{ $7=\"\"; print }'"
)
elif osdata["os_family"] == "AIX":
grains["ps"] = "/usr/bin/ps auxww"
elif osdata["os_family"] == "NILinuxRT":
grains["ps"] = "ps -o user,pid,ppid,tty,time,comm"
else:
grains["ps"] = "ps -efHww"
return grains
def _clean_value(key, val):
"""
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
"""
if val is None or not val or re.match("none", val, flags=re.IGNORECASE):
return None
elif "uuid" in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace("HW %s value %s is an invalid UUID", key, val.replace("\n", " "))
return None
elif re.search("serial|part|version", key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (
re.match(r"^[0]+$", val)
or re.match(r"[0]?1234567[8]?[9]?[0]?", val)
or re.search(
r"sernum|part[_-]?number|specified|filled|applicable",
val,
flags=re.IGNORECASE,
)
):
return None
elif re.search("asset|manufacturer", key):
# AssetTag0. Manufacturer04. Begone.
if re.search(
r"manufacturer|to be filled|available|asset|^no(ne|t)",
val,
flags=re.IGNORECASE,
):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if re.search(r"to be filled", val, flags=re.IGNORECASE) or re.search(
r"un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)",
val,
flags=re.IGNORECASE,
):
return None
return val
def _windows_os_release_grain(caption, product_type):
"""
helper function for getting the osrelease grain
:return:
"""
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = "Unknown"
release = ""
if "Server" in caption:
# Edge case here to handle MS Product that doesn't contain a year
if re.match(r"^Microsoft Hyper-V Server$", caption):
version = "2019"
else:
for item in caption.split(" "):
# If it's all digits, then it's version
if re.match(r"\d+", item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r"^R\d+$", item):
release = item
os_release = "{0}Server{1}".format(version, release)
else:
for item in caption.split(" "):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r"^(\d+(\.\d+)?)|Thin|Vista|XP$", item):
version = item
os_release = version
# If the version is still Unknown, revert back to the old way of getting
# the os_release
# https://github.com/saltstack/salt/issues/52339
if os_release in ["Unknown"]:
os_release = platform.release()
server = {
"Vista": "2008Server",
"7": "2008ServerR2",
"8": "2012Server",
"8.1": "2012ServerR2",
"10": "2016Server",
}
# Starting with Python 2.7.12 and 3.5.2 the `platform.uname()`
# function started reporting the Desktop version instead of the
# Server version on # Server versions of Windows, so we need to look
# those up. So, if you find a Server Platform that's a key in the
# server dictionary, then lookup the actual Server Release.
# (Product Type 1 is Desktop, Everything else is Server)
if product_type > 1 and os_release in server:
os_release = server[os_release]
return os_release
def _windows_platform_data():
"""
Use the platform module for as much as we can.
"""
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {"product": None, "serial": None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard["product"] = motherboardinfo.Product
motherboard["serial"] = motherboardinfo.SerialNumber
except IndexError:
log.debug("Motherboard info not available on this system")
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info["ServicePackMajor"] > 0:
service_pack = "".join(["SP", six.text_type(info["ServicePackMajor"])])
os_release = _windows_os_release_grain(
caption=osinfo.Caption, product_type=osinfo.ProductType
)
grains = {
"kernelrelease": _clean_value("kernelrelease", osinfo.Version),
"kernelversion": _clean_value("kernelversion", kernel_version),
"osversion": _clean_value("osversion", osinfo.Version),
"osrelease": _clean_value("osrelease", os_release),
"osservicepack": _clean_value("osservicepack", service_pack),
"osmanufacturer": _clean_value("osmanufacturer", osinfo.Manufacturer),
"manufacturer": _clean_value("manufacturer", systeminfo.Manufacturer),
"productname": _clean_value("productname", systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
"biosversion": _clean_value("biosversion", biosinfo.Name.strip()),
"serialnumber": _clean_value("serialnumber", biosinfo.SerialNumber),
"osfullname": _clean_value("osfullname", osinfo.Caption),
"timezone": _clean_value("timezone", timeinfo.Description),
"windowsdomain": _clean_value("windowsdomain", net_info["Domain"]),
"windowsdomaintype": _clean_value(
"windowsdomaintype", net_info["DomainType"]
),
"motherboard": {
"productname": _clean_value(
"motherboard.productname", motherboard["product"]
),
"serialnumber": _clean_value(
"motherboard.serialnumber", motherboard["serial"]
),
},
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if "VRTUAL" in biosinfo.Version: # (not a typo)
grains["virtual"] = "HyperV"
elif "A M I" in biosinfo.Version:
grains["virtual"] = "VirtualPC"
elif "VMware" in systeminfo.Model:
grains["virtual"] = "VMware"
elif "VirtualBox" in systeminfo.Model:
grains["virtual"] = "VirtualBox"
elif "Xen" in biosinfo.Version:
grains["virtual"] = "Xen"
if "HVM domU" in systeminfo.Model:
grains["virtual_subtype"] = "HVM domU"
elif "OpenStack" in systeminfo.Model:
grains["virtual"] = "OpenStack"
elif "AMAZON" in biosinfo.Version:
grains["virtual"] = "EC2"
return grains
def _osx_platform_data():
"""
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
"""
cmd = "system_profiler SPHardwareDataType"
hardware = __salt__["cmd.run"](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(": ")
if field_name.strip() == "Model Name":
key = "model_name"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = "boot_rom_version"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = "smc_version"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = "system_serialnumber"
grains[key] = _clean_value(key, field_val)
return grains
def id_():
"""
Return the id
"""
return {"id": __opts__.get("id", "")}
_REPLACE_LINUX_RE = re.compile(r"\W(?:gnu/)?linux", re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
"redhatente": "RedHat",
"gentoobase": "Gentoo",
"archarm": "Arch ARM",
"arch": "Arch",
"debian": "Debian",
"raspbian": "Raspbian",
"fedoraremi": "Fedora",
"chapeau": "Chapeau",
"korora": "Korora",
"amazonami": "Amazon",
"alt": "ALT",
"enterprise": "OEL",
"oracleserv": "OEL",
"cloudserve": "CloudLinux",
"cloudlinux": "CloudLinux",
"pidora": "Fedora",
"scientific": "ScientificLinux",
"synology": "Synology",
"nilrt": "NILinuxRT",
"poky": "Poky",
"manjaro": "Manjaro",
"manjarolin": "Manjaro",
"univention": "Univention",
"antergos": "Antergos",
"sles": "SUSE",
"void": "Void",
"slesexpand": "RES",
"linuxmint": "Mint",
"neon": "KDE neon",
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
"Ubuntu": "Debian",
"Fedora": "RedHat",
"Chapeau": "RedHat",
"Korora": "RedHat",
"FedBerry": "RedHat",
"CentOS": "RedHat",
"GoOSe": "RedHat",
"Scientific": "RedHat",
"Amazon": "RedHat",
"CloudLinux": "RedHat",
"OVS": "RedHat",
"OEL": "RedHat",
"XCP": "RedHat",
"XCP-ng": "RedHat",
"XenServer": "RedHat",
"RES": "RedHat",
"Sangoma": "RedHat",
"Mandrake": "Mandriva",
"ESXi": "VMware",
"Mint": "Debian",
"VMwareESX": "VMware",
"Bluewhite64": "Bluewhite",
"Slamd64": "Slackware",
"SLES": "Suse",
"SUSE Enterprise Server": "Suse",
"SUSE Enterprise Server": "Suse",
"SLED": "Suse",
"openSUSE": "Suse",
"SUSE": "Suse",
"openSUSE Leap": "Suse",
"openSUSE Tumbleweed": "Suse",
"SLES_SAP": "Suse",
"Solaris": "Solaris",
"SmartOS": "Solaris",
"OmniOS": "Solaris",
"OpenIndiana Development": "Solaris",
"OpenIndiana": "Solaris",
"OpenSolaris Development": "Solaris",
"OpenSolaris": "Solaris",
"Oracle Solaris": "Solaris",
"Arch ARM": "Arch",
"Manjaro": "Arch",
"Antergos": "Arch",
"ALT": "RedHat",
"Trisquel": "Debian",
"GCEL": "Debian",
"Linaro": "Debian",
"elementary OS": "Debian",
"elementary": "Debian",
"Univention": "Debian",
"ScientificLinux": "RedHat",
"Raspbian": "Debian",
"Devuan": "Debian",
"antiX": "Debian",
"Kali": "Debian",
"neon": "Debian",
"Cumulus": "Debian",
"Deepin": "Debian",
"NILinuxRT": "NILinuxRT",
"KDE neon": "Debian",
"Void": "Void",
"IDMS": "Debian",
"Funtoo": "Gentoo",
"AIX": "AIX",
"TurnKey": "Debian",
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile(
(
"^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:'|\")?"
"([\\w\\s\\.\\-_]+)(?:'|\")?"
)
)
def _linux_bin_exists(binary):
"""
Does a binary exist in linux (depends on which, type, or whereis)
"""
for search_cmd in ("which", "type -ap"):
try:
return __salt__["cmd.retcode"]("{0} {1}".format(search_cmd, binary)) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return (
len(
__salt__["cmd.run_all"]("whereis -b {0}".format(binary))[
"stdout"
].split()
)
> 1
)
except salt.exceptions.CommandExecutionError:
return False
def _parse_lsb_release():
ret = {}
try:
log.trace("Attempting to parse /etc/lsb-release")
with salt.utils.files.fopen("/etc/lsb-release") as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip("\n")).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret["lsb_{0}".format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace("Failed to parse /etc/lsb-release: %s", exc)
return ret
def _parse_os_release(*os_release_files):
"""
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
"""
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile("^([\\w]+)=(?:'|\")?(.*?)(?:'|\")?$")
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r"\1", match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
"""
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
Note: cpe:2.3:part:vendor:product:version:update:edition:lang:sw_edition:target_sw:target_hw:other
however some OS's do not have the full 13 elements, for example:
CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2"
:param cpe:
:return:
"""
part = {
"o": "operating system",
"h": "hardware",
"a": "application",
}
ret = {}
cpe = (cpe or "").split(":")
if len(cpe) > 4 and cpe[0] == "cpe":
if cpe[1].startswith("/"): # WFN to URI
ret["vendor"], ret["product"], ret["version"] = cpe[2:5]
ret["phase"] = cpe[5] if len(cpe) > 5 else None
ret["part"] = part.get(cpe[1][1:])
elif len(cpe) == 6 and cpe[1] == "2.3": # WFN to a string
ret["vendor"], ret["product"], ret["version"] = [
x if x != "*" else None for x in cpe[3:6]
]
ret["phase"] = None
ret["part"] = part.get(cpe[2])
elif len(cpe) > 7 and len(cpe) <= 13 and cpe[1] == "2.3": # WFN to a string
ret["vendor"], ret["product"], ret["version"], ret["phase"] = [
x if x != "*" else None for x in cpe[3:7]
]
ret["part"] = part.get(cpe[2])
return ret
def os_data():
"""
Return grains pertaining to the operating system
"""
grains = {
"num_gpus": 0,
"gpus": [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(
grains["kernel"],
grains["nodename"],
grains["kernelrelease"],
grains["kernelversion"],
grains["cpuarch"],
_,
) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains["kernel"] = "proxy"
grains["kernelrelease"] = "proxy"
grains["kernelversion"] = "proxy"
grains["osrelease"] = "proxy"
grains["os"] = "proxy"
grains["os_family"] = "proxy"
grains["osfullname"] = "proxy"
elif salt.utils.platform.is_windows():
grains["os"] = "Windows"
grains["os_family"] = "Windows"
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if "Server" in grains["osrelease"]:
osrelease_info = grains["osrelease"].split("Server", 1)
osrelease_info[1] = osrelease_info[1].lstrip("R")
else:
osrelease_info = grains["osrelease"].split(".")
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains["osrelease_info"] = tuple(osrelease_info)
grains["osfinger"] = "{os}-{ver}".format(
os=grains["os"], ver=grains["osrelease"]
)
grains["init"] = "Windows"
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists("selinuxenabled"):
log.trace("Adding selinux grains")
grains["selinux"] = {}
grains["selinux"]["enabled"] = (
__salt__["cmd.retcode"]("selinuxenabled") == 0
)
if _linux_bin_exists("getenforce"):
grains["selinux"]["enforced"] = __salt__["cmd.run"](
"getenforce"
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists("systemctl") and _linux_bin_exists("localectl"):
log.trace("Adding systemd grains")
grains["systemd"] = {}
systemd_info = __salt__["cmd.run"]("systemctl --version").splitlines()
grains["systemd"]["version"] = systemd_info[0].split()[1]
grains["systemd"]["features"] = systemd_info[1]
# Add init grain
grains["init"] = "unknown"
log.trace("Adding init grain")
try:
os.stat("/run/systemd/system")
grains["init"] = "systemd"
except (OSError, IOError):
try:
with salt.utils.files.fopen("/proc/1/cmdline") as fhr:
init_cmdline = fhr.read().replace("\x00", " ").split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning("Unable to fetch data from /proc/1/cmdline")
if init_bin is not None and init_bin.endswith("bin/init"):
supported_inits = (b"upstart", b"sysvinit", b"systemd")
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__["file_buffer_size"]
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, "rb") as fp_:
edge = b""
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode("utf-8")
grains["init"] = item
buf = b""
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
"Unable to read from init_bin (%s): %s", init_bin, exc
)
elif salt.utils.path.which("supervisord") in init_cmdline:
grains["init"] = "supervisord"
elif salt.utils.path.which("dumb-init") in init_cmdline:
# https://github.com/Yelp/dumb-init
grains["init"] = "dumb-init"
elif salt.utils.path.which("tini") in init_cmdline:
# https://github.com/krallin/tini
grains["init"] = "tini"
elif init_cmdline == ["runit"]:
grains["init"] = "runit"
elif "/sbin/my_init" in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains["init"] = "runit"
else:
log.debug(
"Could not determine init system from command line: (%s)",
" ".join(init_cmdline),
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace("Getting lsb_release distro information")
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = "lsb_{0}{1}".format(
"" if key.startswith("distrib_") else "distrib_", key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace("lsb_release python bindings not available")
grains.update(_parse_lsb_release())
if grains.get("lsb_distrib_description", "").lower().startswith("antergos"):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains["osfullname"] = "Antergos Linux"
elif "lsb_distrib_id" not in grains:
log.trace("Failed to get lsb_distrib_id, trying to parse os-release")
os_release = _parse_os_release("/etc/os-release", "/usr/lib/os-release")
if os_release:
if "NAME" in os_release:
grains["lsb_distrib_id"] = os_release["NAME"].strip()
if "VERSION_ID" in os_release:
grains["lsb_distrib_release"] = os_release["VERSION_ID"]
if "VERSION_CODENAME" in os_release:
grains["lsb_distrib_codename"] = os_release["VERSION_CODENAME"]
elif "PRETTY_NAME" in os_release:
codename = os_release["PRETTY_NAME"]
# https://github.com/saltstack/salt/issues/44108
if os_release["ID"] == "debian":
codename_match = re.search(r"\((\w+)\)$", codename)
if codename_match:
codename = codename_match.group(1)
grains["lsb_distrib_codename"] = codename
if "CPE_NAME" in os_release:
cpe = _parse_cpe_name(os_release["CPE_NAME"])
if not cpe:
log.error("Broken CPE_NAME format in /etc/os-release!")
elif cpe.get("vendor", "").lower() in ["suse", "opensuse"]:
grains["os"] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains["osfullname"] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains["osfullname"] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if (
cpe.get("version") and cpe.get("vendor") == "opensuse"
): # Keep VERSION_ID for SLES
grains["lsb_distrib_release"] = cpe["version"]
elif os.path.isfile("/etc/SuSE-release"):
log.trace("Parsing distrib info from /etc/SuSE-release")
grains["lsb_distrib_id"] = "SUSE"
version = ""
patch = ""
with salt.utils.files.fopen("/etc/SuSE-release") as fhr:
for line in fhr:
if "enterprise" in line.lower():
grains["lsb_distrib_id"] = "SLES"
grains["lsb_distrib_codename"] = re.sub(
r"\(.+\)", "", line
).strip()
elif "version" in line.lower():
version = re.sub(r"[^0-9]", "", line)
elif "patchlevel" in line.lower():
patch = re.sub(r"[^0-9]", "", line)
grains["lsb_distrib_release"] = version
if patch:
grains["lsb_distrib_release"] += "." + patch
patchstr = "SP" + patch
if (
grains["lsb_distrib_codename"]
and patchstr not in grains["lsb_distrib_codename"]
):
grains["lsb_distrib_codename"] += " " + patchstr
if not grains.get("lsb_distrib_codename"):
grains["lsb_distrib_codename"] = "n.a"
elif os.path.isfile("/etc/altlinux-release"):
log.trace("Parsing distrib info from /etc/altlinux-release")
# ALT Linux
grains["lsb_distrib_id"] = "altlinux"
with salt.utils.files.fopen("/etc/altlinux-release") as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == "ALT":
grains["lsb_distrib_release"] = comps[2]
grains["lsb_distrib_codename"] = (
comps[3].replace("(", "").replace(")", "")
)
elif os.path.isfile("/etc/centos-release"):
log.trace("Parsing distrib info from /etc/centos-release")
# CentOS Linux
grains["lsb_distrib_id"] = "CentOS"
with salt.utils.files.fopen("/etc/centos-release") as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r"\d+\.\d+")
find_codename = re.compile(r"(?<=\()(.*?)(?=\))")
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains["lsb_distrib_release"] = release.group()
if codename is not None:
grains["lsb_distrib_codename"] = codename.group()
elif os.path.isfile("/etc.defaults/VERSION") and os.path.isfile(
"/etc.defaults/synoinfo.conf"
):
grains["osfullname"] = "Synology"
log.trace(
"Parsing Synology distrib info from /etc/.defaults/VERSION"
)
with salt.utils.files.fopen("/etc.defaults/VERSION", "r") as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip("\n").split("=")
except ValueError:
continue
if key in ("majorversion", "minorversion", "buildnumber"):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
"Unable to determine Synology version info. "
"Please report this, as it is likely a bug."
)
else:
grains[
"osrelease"
] = "{majorversion}.{minorversion}-{buildnumber}".format(
**synoinfo
)
log.trace(
"Getting OS name, release, and codename from distro id, version, codename"
)
(osname, osrelease, oscodename) = [
x.strip('"').strip("'") for x in _linux_distribution()
]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if "osfullname" not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get("lsb_distrib_id", "").lower().startswith("nilrt"):
grains["osfullname"] = "nilrt"
else:
grains["osfullname"] = grains.get("lsb_distrib_id", osname).strip()
if "osrelease" not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
# This also affects Centos 8
if any(
os in grains.get("lsb_distrib_codename", "")
for os in ["CentOS Linux 7", "CentOS Linux 8"]
):
grains.pop("lsb_distrib_release", None)
grains["osrelease"] = grains.get("lsb_distrib_release", osrelease).strip()
grains["oscodename"] = (
grains.get("lsb_distrib_codename", "").strip() or oscodename
)
if "Red Hat" in grains["oscodename"]:
grains["oscodename"] = oscodename
distroname = _REPLACE_LINUX_RE.sub("", grains["osfullname"]).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(" ", "").lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if "os" not in grains:
grains["os"] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains["kernel"] == "SunOS":
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index("_") + 1 :]
grains["os"] = grains["osfullname"] = "SmartOS"
# store a parsed version of YYYY.MM.DD as osrelease
grains["osrelease"] = ".".join(
[
uname_v.split("T")[0][0:4],
uname_v.split("T")[0][4:6],
uname_v.split("T")[0][6:8],
]
)
# store a untouched copy of the timestamp in osrelease_stamp
grains["osrelease_stamp"] = uname_v
elif os.path.isfile("/etc/release"):
with salt.utils.files.fopen("/etc/release", "r") as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r"((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?"
r"\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?"
)
(
osname,
development,
osmajorrelease,
osminorrelease,
) = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains["os"] = grains["osfullname"] = "Solaris"
grains["osrelease"] = ""
else:
if development is not None:
osname = " ".join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains["os"] = grains["osfullname"] = osname
if osname in ["Oracle Solaris"] and uname_v.startswith(
osmajorrelease
):
# Oracla Solars 11 and up have minor version in uname
grains["osrelease"] = uname_v
elif osname in ["OmniOS"]:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains["osrelease"] = ".".join(osrelease)
grains["osrelease_stamp"] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains["osrelease"] = ".".join(osrelease)
grains["osrelease_stamp"] = uname_v
grains.update(_sunos_cpudata())
elif grains["kernel"] == "VMkernel":
grains["os"] = "ESXi"
elif grains["kernel"] == "Darwin":
osrelease = __salt__["cmd.run"]("sw_vers -productVersion")
osname = __salt__["cmd.run"]("sw_vers -productName")
osbuild = __salt__["cmd.run"]("sw_vers -buildVersion")
grains["os"] = "MacOS"
grains["os_family"] = "MacOS"
grains["osfullname"] = "{0} {1}".format(osname, osrelease)
grains["osrelease"] = osrelease
grains["osbuild"] = osbuild
grains["init"] = "launchd"
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains["kernel"] == "AIX":
osrelease = __salt__["cmd.run"]("oslevel")
osrelease_techlevel = __salt__["cmd.run"]("oslevel -r")
osname = __salt__["cmd.run"]("uname")
grains["os"] = "AIX"
grains["osfullname"] = osname
grains["osrelease"] = osrelease
grains["osrelease_techlevel"] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains["os"] = grains["kernel"]
if grains["kernel"] == "FreeBSD":
grains["osfullname"] = grains["os"]
try:
grains["osrelease"] = __salt__["cmd.run"]("freebsd-version -u").split("-")[
0
]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains["osrelease"] = grains["kernelrelease"].split("-")[0]
grains.update(_bsd_cpudata(grains))
if grains["kernel"] in ("OpenBSD", "NetBSD"):
grains.update(_bsd_cpudata(grains))
grains["osrelease"] = grains["kernelrelease"].split("-")[0]
if grains["kernel"] == "NetBSD":
grains.update(_netbsd_gpu_data())
if not grains["os"]:
grains["os"] = "Unknown {0}".format(grains["kernel"])
grains["os_family"] = "Unknown"
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains["os_family"] = _OS_FAMILY_MAP.get(grains["os"], grains["os"])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get("os_family") == "Debian":
osarch = __salt__["cmd.run"]("dpkg --print-architecture").strip()
elif grains.get("os_family") in ["RedHat", "Suse"]:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get("os_family") in ("NILinuxRT", "Poky"):
archinfo = {}
for line in __salt__["cmd.run"]("opkg print-architecture").splitlines():
if line.startswith("arch"):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains["cpuarch"]
grains["osarch"] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get("osrelease", ""):
osrelease_info = grains["osrelease"].split(".")
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains["osrelease_info"] = tuple(osrelease_info)
try:
grains["osmajorrelease"] = int(grains["osrelease_info"][0])
except (IndexError, TypeError, ValueError):
log.debug(
"Unable to derive osmajorrelease from osrelease_info '%s'. "
"The osmajorrelease grain will not be set.",
grains["osrelease_info"],
)
os_name = grains[
"os"
if grains.get("os")
in ("Debian", "FreeBSD", "OpenBSD", "NetBSD", "Mac", "Raspbian")
else "osfullname"
]
grains["osfinger"] = "{0}-{1}".format(
os_name,
grains["osrelease"]
if os_name in ("Ubuntu",)
else grains["osrelease_info"][0],
)
return grains
def locale_info():
"""
Provides
defaultlanguage
defaultencoding
"""
grains = {}
grains["locale_info"] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains["locale_info"]["defaultlanguage"],
grains["locale_info"]["defaultencoding"],
) = locale.getdefaultlocale()
except Exception: # pylint: disable=broad-except
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains["locale_info"]["defaultlanguage"] = "unknown"
grains["locale_info"]["defaultencoding"] = "unknown"
grains["locale_info"]["detectedencoding"] = __salt_system_encoding__
grains["locale_info"]["timezone"] = "unknown"
if _DATEUTIL_TZ:
try:
grains["locale_info"]["timezone"] = datetime.datetime.now(
dateutil.tz.tzlocal()
).tzname()
except UnicodeDecodeError:
# Because the method 'tzname' is not a part of salt the decoding error cant be fixed.
# The error is in datetime in the python2 lib
if salt.utils.platform.is_windows():
grains["locale_info"]["timezone"] = time.tzname[0].decode("mbcs")
return grains
def hostname():
"""
Return fqdn, hostname, domainname
.. note::
On Windows the ``domain`` grain may refer to the dns entry for the host
instead of the Windows domain to which the host is joined. It may also
be empty if not a part of any domain. Refer to the ``windowsdomain``
grain instead
"""
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains["localhost"] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error(
"Having trouble getting a hostname. Does this machine have its hostname and domain set properly?"
)
__FQDN__ = "localhost.localdomain"
grains["fqdn"] = __FQDN__
(grains["host"], grains["domain"]) = grains["fqdn"].partition(".")[::2]
return grains
def append_domain():
"""
Return append_domain if set
"""
grain = {}
if salt.utils.platform.is_proxy():
return grain
if "append_domain" in __opts__:
grain["append_domain"] = __opts__["append_domain"]
return grain
def fqdns():
"""
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
To disable the fqdns grain, set enable_fqdns_grains: False in the minion configuration file.
"""
# Provides:
# fqdns
opt = {"fqdns": []}
if __opts__.get(
"enable_fqdns_grains",
False
if salt.utils.platform.is_windows() or salt.utils.platform.is_proxy()
else True,
):
opt = __salt__["network.fqdns"]()
return opt
def ip_fqdn():
"""
Return ip address and FQDN grains
"""
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret["ipv4"] = salt.utils.network.ip_addrs(include_loopback=True)
ret["ipv6"] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()["fqdn"]
for socket_type, ipv_num in ((socket.AF_INET, "4"), (socket.AF_INET6, "6")):
key = "fqdn_ip" + ipv_num
if not ret["ipv" + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except (socket.error, UnicodeError):
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__["__role"] == "master":
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
"second timeout when rendering grains. Set the dns or "
"/etc/hosts for IPv%s to clear this.",
ipv_num,
_fqdn,
timediff,
ipv_num,
)
ret[key] = []
return ret
def ip_interfaces():
"""
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
"""
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet", []):
if "address" in inet:
iface_ips.append(inet["address"])
for inet in ifaces[face].get("inet6", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip_interfaces": ret}
def ip4_interfaces():
"""
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
"""
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip4_interfaces": ret}
def ip6_interfaces():
"""
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
"""
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet6", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip6_interfaces": ret}
def hwaddr_interfaces():
"""
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
"""
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if "hwaddr" in ifaces[face]:
ret[face] = ifaces[face]["hwaddr"]
return {"hwaddr_interfaces": ret}
def dns():
"""
Parse the resolver configuration file
.. versionadded:: 2016.3.0
"""
# Provides:
# dns
if salt.utils.platform.is_windows() or "proxyminion" in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ("nameservers", "ip4_nameservers", "ip6_nameservers", "sortlist"):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {"dns": resolv} if resolv else {}
def get_machine_id():
"""
Provide the machine-id for machine/virtualization combination
"""
# Provides:
# machine-id
if platform.system() == "AIX":
return _aix_get_machine_id()
locations = ["/etc/machine-id", "/var/lib/dbus/machine-id"]
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {"machine_id": machineid.read().strip()}
def cwd():
"""
Current working directory
"""
return {"cwd": os.getcwd()}
def path():
"""
Return the path
"""
# Provides:
# path
# systempath
_path = salt.utils.stringutils.to_unicode(os.environ.get("PATH", "").strip())
return {
"path": _path,
"systempath": _path.split(os.path.pathsep),
}
def pythonversion():
"""
Return the Python version
"""
# Provides:
# pythonversion
return {"pythonversion": list(sys.version_info)}
def pythonpath():
"""
Return the Python path
"""
# Provides:
# pythonpath
return {"pythonpath": sys.path}
def pythonexecutable():
"""
Return the python executable in use
"""
# Provides:
# pythonexecutable
return {"pythonexecutable": sys.executable}
def saltpath():
"""
Return the path of the salt module
"""
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {"saltpath": os.path.dirname(salt_path)}
def saltversion():
"""
Return the version of salt
"""
# Provides:
# saltversion
from salt.version import __version__
return {"saltversion": __version__}
def zmqversion():
"""
Return the zeromq version
"""
# Provides:
# zmqversion
try:
import zmq
return {"zmqversion": zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
"""
Return the version_info of salt
.. versionadded:: 0.17.0
"""
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {"saltversioninfo": list(__version_info__)}
def _hw_data(osdata):
"""
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
"""
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata["kernel"] == "Linux" and os.path.exists("/sys/class/dmi/id"):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
"biosversion": "bios_version",
"productname": "product_name",
"manufacturer": "sys_vendor",
"biosreleasedate": "bios_date",
"uuid": "product_uuid",
"serialnumber": "product_serial",
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join("/sys/class/dmi/id", fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, "r") as ifile:
grains[key] = salt.utils.stringutils.to_unicode(
ifile.read().strip(), errors="replace"
)
if key == "uuid":
grains["uuid"] = grains["uuid"].lower()
except UnicodeDecodeError:
# Some firmwares provide non-valid 'product_name'
# files, ignore them
log.debug(
"The content in /sys/devices/virtual/dmi/id/product_name is not valid"
)
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(["dmidecode", "smbios"]) is not None and not (
salt.utils.platform.is_smartos()
or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata["kernel"] == "SunOS" and osdata["cpuarch"].startswith("sparc")
)
):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
"biosversion": __salt__["smbios.get"]("bios-version"),
"productname": __salt__["smbios.get"]("system-product-name"),
"manufacturer": __salt__["smbios.get"]("system-manufacturer"),
"biosreleasedate": __salt__["smbios.get"]("bios-release-date"),
"uuid": __salt__["smbios.get"]("system-uuid"),
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__["smbios.get"]("system-uuid")
if uuid is not None:
grains["uuid"] = uuid.lower()
for serial in (
"system-serial-number",
"chassis-serial-number",
"baseboard-serial-number",
):
serial = __salt__["smbios.get"](serial)
if serial is not None:
grains["serialnumber"] = serial
break
elif salt.utils.path.which_bin(["fw_printenv"]) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
"manufacturer": "manufacturer",
"serialnumber": "serial#",
"productname": "DeviceDesc",
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__["cmd.run_all"]("fw_printenv {0}".format(cmd_key))
if result["retcode"] == 0:
uboot_keyval = result["stdout"].split("=")
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata["kernel"] == "FreeBSD":
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which("kenv")
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
"biosversion": "smbios.bios.version",
"manufacturer": "smbios.system.maker",
"serialnumber": "smbios.system.serial",
"productname": "smbios.system.product",
"biosreleasedate": "smbios.bios.reldate",
"uuid": "smbios.system.uuid",
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__["cmd.run"]("{0} {1}".format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "OpenBSD":
sysctl = salt.utils.path.which("sysctl")
hwdata = {
"biosversion": "hw.version",
"manufacturer": "hw.vendor",
"productname": "hw.product",
"serialnumber": "hw.serialno",
"uuid": "hw.uuid",
}
for key, oid in six.iteritems(hwdata):
value = __salt__["cmd.run"]("{0} -n {1}".format(sysctl, oid))
if not value.endswith(" value is not available"):
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "NetBSD":
sysctl = salt.utils.path.which("sysctl")
nbsd_hwdata = {
"biosversion": "machdep.dmi.board-version",
"manufacturer": "machdep.dmi.system-vendor",
"serialnumber": "machdep.dmi.system-serial",
"productname": "machdep.dmi.system-product",
"biosreleasedate": "machdep.dmi.bios-date",
"uuid": "machdep.dmi.system-uuid",
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__["cmd.run_all"]("{0} -n {1}".format(sysctl, oid))
if result["retcode"] == 0:
grains[key] = _clean_value(key, result["stdout"])
elif osdata["kernel"] == "Darwin":
grains["manufacturer"] = "Apple Inc."
sysctl = salt.utils.path.which("sysctl")
hwdata = {"productname": "hw.model"}
for key, oid in hwdata.items():
value = __salt__["cmd.run"]("{0} -b {1}".format(sysctl, oid))
if not value.endswith(" is invalid"):
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "SunOS" and osdata["cpuarch"].startswith("sparc"):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (
("/usr/sbin/prtdiag", "-v"),
("/usr/sbin/prtconf", "-vp"),
("/usr/sbin/virtinfo", "-a"),
):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__["cmd.run"]("{0} {1}".format(cmd, args))
data += "\n"
sn_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)", # prtdiag
r"(?im)^\s*chassis-sn:\s*(\S+)", # prtconf
r"(?im)^\s*Chassis\s+Serial#:\s*(\S+)", # virtinfo
]
]
obp_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)", # prtdiag
r"(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)", # prtconf
]
]
fw_regexes = [
re.compile(r)
for r in [r"(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)"] # prtdiag
]
uuid_regexes = [
re.compile(r) for r in [r"(?im)^\s*Domain\s+UUID:\s*(\S+)"] # virtinfo
]
manufacture_regexes = [
re.compile(r)
for r in [r"(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)"] # prtdiag
]
product_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)", # prtdiag
r"(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)", # prtconf
r"(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)", # prtconf
]
]
sn_regexes = [
re.compile(r)
for r in [
r"(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)", # prtdiag
r"(?i)Chassis\s+Serial#:\s*(\S+)", # virtinfo
r"(?i)chassis-sn:\s*(\S+)", # prtconf
]
]
obp_regexes = [
re.compile(r)
for r in [
r"(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)", # prtdiag
r"(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)", # prtconf
]
]
fw_regexes = [
re.compile(r)
for r in [r"(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)"] # prtdiag
]
uuid_regexes = [
re.compile(r) for r in [r"(?i)Domain\s+UUID:\s+(\S+)"] # virtinfo
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["serialnumber"] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[
0:2
] # Limit the number in case we found the data in multiple places
grains["biosversion"] = obp_rev.strip().replace("'", "")
grains["biosreleasedate"] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains["systemfirmware"] = fw_rev.strip().replace("'", "")
grains["systemfirmwaredate"] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["uuid"] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["manufacture"] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains["product"] = t_productname
grains["productname"] = t_productname
break
elif osdata["kernel"] == "AIX":
cmd = salt.utils.path.which("prtconf")
if cmd:
data = __salt__["cmd.run"]("{0}".format(cmd)) + os.linesep
for dest, regstring in (
("serialnumber", r"(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)"),
("systemfirmware", r"(?im)^\s*Firmware\s+Version:\s+(.*)"),
):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", "")
product_regexes = [re.compile(r"(?im)^\s*System\s+Model:\s+(\S+)")]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["manufacturer"], grains["productname"] = (
res.group(1).strip().replace("'", "").split(",")
)
break
else:
log.error("The 'prtconf' binary was not found in $PATH.")
return grains
def get_server_id():
"""
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
"""
# Provides:
# server_id
if salt.utils.platform.is_proxy():
return {}
id_ = __opts__.get("id", "")
hash_ = int(hashlib.sha256(id_.encode()).hexdigest(), 16)
return {"server_id": abs(hash_ % (2 ** 31))}
def get_master():
"""
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
"""
# Provides:
# master
return {"master": __opts__.get("master", "")}
def default_gateway():
"""
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
"""
grains = {}
ip_bin = salt.utils.path.which("ip")
if not ip_bin:
return {}
grains["ip_gw"] = False
grains["ip4_gw"] = False
grains["ip6_gw"] = False
for ip_version in ("4", "6"):
try:
out = __salt__["cmd.run"]([ip_bin, "-" + ip_version, "route", "show"])
for line in out.splitlines():
if line.startswith("default"):
grains["ip_gw"] = True
grains["ip{0}_gw".format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == "via":
grains["ip{0}_gw".format(ip_version)] = gw_ip
break
except Exception: # pylint: disable=broad-except
continue
return grains
def kernelparams():
"""
Return the kernel boot parameters
"""
try:
with salt.utils.files.fopen("/proc/cmdline", "r") as fhr:
cmdline = fhr.read()
grains = {"kernelparams": []}
for data in [
item.split("=") for item in salt.utils.args.shlex_split(cmdline)
]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains["kernelparams"] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug("Failed to read /proc/cmdline: %s", exc)
return grains
| 36.911765 | 124 | 0.528985 |
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import hashlib
import locale
import logging
import os
import platform
import re
import socket
import sys
import time
import uuid
from errno import EACCES, EPERM
import distro
import salt.exceptions
import salt.log
import salt.modules.cmdmod
import salt.modules.network
import salt.modules.smbios
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
from salt.utils.network import _get_interfaces
def _linux_distribution():
return (
distro.id(),
distro.version(best=True),
distro.codename(),
)
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
try:
import wmi
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
"Unable to import Python wmi module, some core grains " "will be missing"
)
__proxyenabled__ = ["*"]
__FQDN__ = None
__salt__ = {
"cmd.run": salt.modules.cmdmod._run_quiet,
"cmd.retcode": salt.modules.cmdmod._retcode_quiet,
"cmd.run_all": salt.modules.cmdmod._run_all_quiet,
"smbios.records": salt.modules.smbios.records,
"smbios.get": salt.modules.smbios.get,
"network.fqdns": salt.modules.network.fqdns,
}
HAS_UNAME = hasattr(os, "uname")
HOST_NOT_FOUND = 1
NO_DATA = 4
def _windows_cpudata():
grains = {}
if "NUMBER_OF_PROCESSORS" in os.environ:
# conditional in templating. Also follows _linux_cpudata()
try:
grains["num_cpus"] = int(os.environ["NUMBER_OF_PROCESSORS"])
except ValueError:
grains["num_cpus"] = 1
grains["cpu_model"] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString",
).get("vdata")
return grains
def _linux_cpudata():
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = "/proc/cpuinfo"
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, "r") as _fp:
for line in _fp:
comps = line.split(":")
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == "processor":
grains["num_cpus"] = int(val) + 1
# head -2 /proc/cpuinfo
# vendor_id : IBM/S390
# # processors : 2
elif key == "# processors":
grains["num_cpus"] = int(val)
elif key == "vendor_id":
grains["cpu_model"] = val
elif key == "model name":
grains["cpu_model"] = val
elif key == "flags":
grains["cpu_flags"] = val.split()
elif key == "Features":
grains["cpu_flags"] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == "Processor":
grains["cpu_model"] = val.split("-")[0]
grains["num_cpus"] = 1
if "num_cpus" not in grains:
grains["num_cpus"] = 0
if "cpu_model" not in grains:
grains["cpu_model"] = "Unknown"
if "cpu_flags" not in grains:
grains["cpu_flags"] = []
return grains
def _linux_gpu_data():
if __opts__.get("enable_lspci", True) is False:
return {}
if __opts__.get("enable_gpu_grains", True) is False:
return {}
lspci = salt.utils.path.which("lspci")
if not lspci:
log.debug(
"The `lspci` binary is not available on the system. GPU grains "
"will not be available."
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = [
"nvidia",
"amd",
"ati",
"intel",
"cirrus logic",
"vmware",
"matrox",
"aspeed",
]
gpu_classes = ("vga compatible controller", "3d controller", "display controller")
devs = []
try:
lspci_out = __salt__["cmd.run"]("{0} -vmm".format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append("")
for line in lspci_list:
# check for record-separating empty lines
if line == "":
if cur_dev.get("Class", "").lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r"^\w+:\s+.*", line):
key, val = line.split(":", 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug("Unexpected lspci output: '%s'", line)
if error:
log.warning(
"Error loading grains, unexpected linux_gpu_data output, "
"check that you have a valid shell configured and "
"permissions to run lspci command"
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split("[^A-Za-z0-9]", gpu["Vendor"].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = "unknown"
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({"vendor": vendor, "model": gpu["Device"]})
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _netbsd_gpu_data():
known_vendors = [
"nvidia",
"amd",
"ati",
"intel",
"cirrus logic",
"vmware",
"matrox",
"aspeed",
]
gpus = []
try:
pcictl_out = __salt__["cmd.run"]("pcictl pci0 list")
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r"[0-9:]+ ({0}) (.+) \(VGA .+\)".format(vendor), line, re.IGNORECASE
)
if vendor_match:
gpus.append(
{
"vendor": vendor_match.group(1),
"model": vendor_match.group(2),
}
)
except OSError:
pass
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _osx_gpudata():
gpus = []
try:
pcictl_out = __salt__["cmd.run"]("system_profiler SPDisplaysDataType")
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(": ")
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(" ")
vendor = vendor.lower()
gpus.append({"vendor": vendor, "model": model})
except OSError:
pass
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _bsd_cpudata(osdata):
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which("sysctl")
arch = salt.utils.path.which("arch")
cmds = {}
if sysctl:
cmds.update(
{
"num_cpus": "{0} -n hw.ncpu".format(sysctl),
"cpuarch": "{0} -n hw.machine".format(sysctl),
"cpu_model": "{0} -n hw.model".format(sysctl),
}
)
if arch and osdata["kernel"] == "OpenBSD":
cmds["cpuarch"] = "{0} -s".format(arch)
if osdata["kernel"] == "Darwin":
cmds["cpu_model"] = "{0} -n machdep.cpu.brand_string".format(sysctl)
cmds["cpu_flags"] = "{0} -n machdep.cpu.features".format(sysctl)
grains = dict([(k, __salt__["cmd.run"](v)) for k, v in six.iteritems(cmds)])
if "cpu_flags" in grains and isinstance(grains["cpu_flags"], six.string_types):
grains["cpu_flags"] = grains["cpu_flags"].split(" ")
if osdata["kernel"] == "NetBSD":
grains["cpu_flags"] = []
for line in __salt__["cmd.run"]("cpuctl identify 0").splitlines():
cpu_match = re.match(r"cpu[0-9]:\ features[0-9]?\ .+<(.+)>", line)
if cpu_match:
flag = cpu_match.group(1).split(",")
grains["cpu_flags"].extend(flag)
if osdata["kernel"] == "FreeBSD" and os.path.isfile("/var/run/dmesg.boot"):
grains["cpu_flags"] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen("/var/run/dmesg.boot", "r") as _fp:
cpu_here = False
for line in _fp:
if line.startswith("CPU: "):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(" "):
break # game over
if "Features" in line:
start = line.find("<")
end = line.find(">")
if start > 0 and end > 0:
flag = line[start + 1 : end].split(",")
grains["cpu_flags"].extend(flag)
try:
grains["num_cpus"] = int(grains["num_cpus"])
except ValueError:
grains["num_cpus"] = 1
return grains
def _sunos_cpudata():
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains["cpu_flags"] = []
grains["cpuarch"] = __salt__["cmd.run"]("isainfo -k")
psrinfo = "/usr/sbin/psrinfo 2>/dev/null"
grains["num_cpus"] = len(
__salt__["cmd.run"](psrinfo, python_shell=True).splitlines()
)
kstat_info = "kstat -p cpu_info:*:*:brand"
for line in __salt__["cmd.run"](kstat_info).splitlines():
match = re.match(r"(\w+:\d+:\w+\d+:\w+)\s+(.+)", line)
if match:
grains["cpu_model"] = match.group(2)
isainfo = "isainfo -n -v"
for line in __salt__["cmd.run"](isainfo).splitlines():
match = re.match(r"^\s+(.+)", line)
if match:
cpu_flags = match.group(1).split()
grains["cpu_flags"].extend(cpu_flags)
return grains
def _aix_cpudata():
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which("prtconf")
if cmd:
data = __salt__["cmd.run"]("{0}".format(cmd)) + os.linesep
for dest, regstring in (
("cpuarch", r"(?im)^\s*Processor\s+Type:\s+(\S+)"),
("cpu_flags", r"(?im)^\s*Processor\s+Version:\s+(\S+)"),
("cpu_model", r"(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)"),
("num_cpus", r"(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)"),
):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", "")
else:
log.error("The 'prtconf' binary was not found in $PATH.")
return grains
def _linux_memdata():
grains = {"mem_total": 0, "swap_total": 0}
meminfo = "/proc/meminfo"
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, "r") as ifile:
for line in ifile:
comps = line.rstrip("\n").split(":")
if not len(comps) > 1:
continue
if comps[0].strip() == "MemTotal":
grains["mem_total"] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == "SwapTotal":
grains["swap_total"] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
grains = {"mem_total": 0, "swap_total": 0}
sysctl = salt.utils.path.which("sysctl")
if sysctl:
mem = __salt__["cmd.run"]("{0} -n hw.memsize".format(sysctl))
swap_total = (
__salt__["cmd.run"]("{0} -n vm.swapusage".format(sysctl))
.split()[2]
.replace(",", ".")
)
if swap_total.endswith("K"):
_power = 2 ** 10
elif swap_total.endswith("M"):
_power = 2 ** 20
elif swap_total.endswith("G"):
_power = 2 ** 30
swap_total = float(swap_total[:-1]) * _power
grains["mem_total"] = int(mem) // 1024 // 1024
grains["swap_total"] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
grains = {"mem_total": 0, "swap_total": 0}
sysctl = salt.utils.path.which("sysctl")
if sysctl:
mem = __salt__["cmd.run"]("{0} -n hw.physmem".format(sysctl))
if osdata["kernel"] == "NetBSD" and mem.startswith("-"):
mem = __salt__["cmd.run"]("{0} -n hw.physmem64".format(sysctl))
grains["mem_total"] = int(mem) // 1024 // 1024
if osdata["kernel"] in ["OpenBSD", "NetBSD"]:
swapctl = salt.utils.path.which("swapctl")
swap_data = __salt__["cmd.run"]("{0} -sk".format(swapctl))
if swap_data == "no swap devices configured":
swap_total = 0
else:
swap_total = swap_data.split(" ")[1]
else:
swap_total = __salt__["cmd.run"]("{0} -n vm.swap_total".format(sysctl))
grains["swap_total"] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
grains = {"mem_total": 0, "swap_total": 0}
prtconf = "/usr/sbin/prtconf 2>/dev/null"
for line in __salt__["cmd.run"](prtconf, python_shell=True).splitlines():
comps = line.split(" ")
if comps[0].strip() == "Memory" and comps[1].strip() == "size:":
grains["mem_total"] = int(comps[2].strip())
swap_cmd = salt.utils.path.which("swap")
swap_data = __salt__["cmd.run"]("{0} -s".format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains["swap_total"] = swap_total
return grains
def _aix_memdata():
grains = {"mem_total": 0, "swap_total": 0}
prtconf = salt.utils.path.which("prtconf")
if prtconf:
for line in __salt__["cmd.run"](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(" ") if x]
if len(comps) > 2 and "Memory" in comps[0] and "Size" in comps[1]:
grains["mem_total"] = int(comps[2])
break
else:
log.error("The 'prtconf' binary was not found in $PATH.")
swap_cmd = salt.utils.path.which("swap")
if swap_cmd:
swap_data = __salt__["cmd.run"]("{0} -s".format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains["swap_total"] = swap_total
else:
log.error("The 'swap' binary was not found in $PATH.")
return grains
def _windows_memdata():
grains = {"mem_total": 0}
tot_bytes = win32api.GlobalMemoryStatusEx()["TotalPhys"]
grains["mem_total"] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
grains = {"mem_total": 0}
if osdata["kernel"] == "Linux":
grains.update(_linux_memdata())
elif osdata["kernel"] in ("FreeBSD", "OpenBSD", "NetBSD"):
grains.update(_bsd_memdata(osdata))
elif osdata["kernel"] == "Darwin":
grains.update(_osx_memdata())
elif osdata["kernel"] == "SunOS":
grains.update(_sunos_memdata())
elif osdata["kernel"] == "AIX":
grains.update(_aix_memdata())
elif osdata["kernel"] == "Windows" and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
grains = {}
cmd = salt.utils.path.which("lsattr")
if cmd:
data = __salt__["cmd.run"]("{0} -El sys0".format(cmd)) + os.linesep
uuid_regexes = [re.compile(r"(?im)^\s*os_uuid\s+(\S+)\s+(.*)")]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["machine_id"] = res.group(1).strip()
break
else:
log.error("The 'lsattr' binary was not found in $PATH.")
return grains
def _windows_virtual(osdata):
grains = dict()
if osdata["kernel"] != "Windows":
return grains
grains["virtual"] = osdata.get("virtual", "physical")
manufacturer = osdata.get("manufacturer", "")
if manufacturer is None:
manufacturer = ""
productname = osdata.get("productname", "")
if productname is None:
productname = ""
if "QEMU" in manufacturer:
grains["virtual"] = "kvm"
if "Bochs" in manufacturer:
grains["virtual"] = "kvm"
elif "oVirt" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "oVirt"
elif "RHEV Hypervisor" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
elif "VirtualBox" in productname:
grains["virtual"] = "VirtualBox"
elif "VMware Virtual Platform" in productname:
grains["virtual"] = "VMware"
elif "Microsoft" in manufacturer and "Virtual Machine" in productname:
grains["virtual"] = "VirtualPC"
elif "Parallels Software" in manufacturer:
grains["virtual"] = "Parallels"
elif "CloudStack KVM Hypervisor" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "cloudstack"
return grains
def _virtual(osdata):
grains = {"virtual": osdata.get("virtual", "physical")}
skip_cmds = ("AIX",)
_cmds = ["systemd-detect-virt", "virt-what", "dmidecode"]
if not salt.utils.platform.is_windows() and osdata["kernel"] not in skip_cmds:
if salt.utils.path.which("virt-what"):
_cmds = ["virt-what"]
if __opts__.get("enable_lspci", True) is True:
if os.path.exists("/proc/bus/pci"):
_cmds += ["lspci"]
if osdata["kernel"] in skip_cmds:
_cmds = ()
if (
HAS_UNAME
and osdata["kernel"] == "Linux"
and "BrandZ virtual linux" in os.uname()
):
grains["virtual"] = "zone"
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata["kernel"] == "Darwin":
command = "system_profiler"
args = ["SPDisplaysDataType"]
elif osdata["kernel"] == "SunOS":
virtinfo = salt.utils.path.which("virtinfo")
if virtinfo:
try:
ret = __salt__["cmd.run_all"](virtinfo)
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret["stdout"].endswith("not supported"):
command = "prtdiag"
else:
command = "virtinfo"
args.append("-c current list -H -o name")
else:
command = "prtdiag"
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = "{0} {1}".format(cmd, " ".join(args))
try:
ret = __salt__["cmd.run_all"](cmd)
if ret["retcode"] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if (
salt.utils.platform.is_windows()
or "systemd-detect-virt" in cmd
or "prtdiag" in cmd
):
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret["stdout"]
if command == "system_profiler":
macoutput = output.lower()
if "0x1ab8" in macoutput:
grains["virtual"] = "Parallels"
if "parallels" in macoutput:
grains["virtual"] = "Parallels"
if "vmware" in macoutput:
grains["virtual"] = "VMware"
if "0x15ad" in macoutput:
grains["virtual"] = "VMware"
if "virtualbox" in macoutput:
grains["virtual"] = "VirtualBox"
# Break out of the loop so the next log message is not issued
break
elif command == "systemd-detect-virt":
if output in (
"qemu",
"kvm",
"oracle",
"xen",
"bochs",
"chroot",
"uml",
"systemd-nspawn",
):
grains["virtual"] = output
break
elif "vmware" in output:
grains["virtual"] = "VMware"
break
elif "microsoft" in output:
grains["virtual"] = "VirtualPC"
break
elif "lxc" in output:
grains["virtual"] = "LXC"
break
elif "systemd-nspawn" in output:
grains["virtual"] = "LXC"
break
elif command == "virt-what":
for line in output.splitlines():
if line in ("kvm", "qemu", "uml", "xen", "lxc"):
grains["virtual"] = line
break
elif "vmware" in line:
grains["virtual"] = "VMware"
break
elif "parallels" in line:
grains["virtual"] = "Parallels"
break
elif "hyperv" in line:
grains["virtual"] = "HyperV"
break
elif command == "dmidecode":
# Product Name: VirtualBox
if "Vendor: QEMU" in output:
# FIXME: Make this detect between kvm or qemu
grains["virtual"] = "kvm"
if "Manufacturer: QEMU" in output:
grains["virtual"] = "kvm"
if "Vendor: Bochs" in output:
grains["virtual"] = "kvm"
if "Manufacturer: Bochs" in output:
grains["virtual"] = "kvm"
if "BHYVE" in output:
grains["virtual"] = "bhyve"
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif "Manufacturer: oVirt" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "ovirt"
# Red Hat Enterprise Virtualization
elif "Product Name: RHEV Hypervisor" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
elif "VirtualBox" in output:
grains["virtual"] = "VirtualBox"
# Product Name: VMware Virtual Platform
elif "VMware" in output:
grains["virtual"] = "VMware"
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ": Microsoft" in output and "Virtual Machine" in output:
grains["virtual"] = "VirtualPC"
# Manufacturer: Parallels Software International Inc.
elif "Parallels Software" in output:
grains["virtual"] = "Parallels"
elif "Manufacturer: Google" in output:
grains["virtual"] = "kvm"
# Proxmox KVM
elif "Vendor: SeaBIOS" in output:
grains["virtual"] = "kvm"
# Break out of the loop, lspci parsing is not necessary
break
elif command == "lspci":
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if "vmware" in model:
grains["virtual"] = "VMware"
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif "virtualbox" in model:
grains["virtual"] = "VirtualBox"
elif "qemu" in model:
grains["virtual"] = "kvm"
elif "virtio" in model:
grains["virtual"] = "kvm"
# Break out of the loop so the next log message is not issued
break
elif command == "prtdiag":
model = output.lower().split("\n")[0]
if "vmware" in model:
grains["virtual"] = "VMware"
elif "virtualbox" in model:
grains["virtual"] = "VirtualBox"
elif "qemu" in model:
grains["virtual"] = "kvm"
elif "joyent smartdc hvm" in model:
grains["virtual"] = "kvm"
break
elif command == "virtinfo":
if output == "logical-domain":
grains["virtual"] = "LDOM"
roles = []
for role in ("control", "io", "root", "service"):
subtype_cmd = "{0} -c current get -H -o value {1}-role".format(
command, role
)
ret = __salt__["cmd.run"]("{0}".format(subtype_cmd))
if ret == "true":
roles.append(role)
if roles:
grains["virtual_subtype"] = roles
elif output == "non-global-zone":
grains["virtual"] = "zone"
grains["virtual_subtype"] = "non-global"
elif output == "kernel-zone":
grains["virtual"] = "zone"
grains["virtual_subtype"] = "kernel"
elif output == "vmware":
grains["virtual"] = "VMware"
break
choices = ("Linux", "HP-UX")
isdir = os.path.isdir
sysctl = salt.utils.path.which("sysctl")
if osdata["kernel"] in choices:
if os.path.isdir("/proc"):
try:
self_root = os.stat("/")
init_root = os.stat("/proc/1/root/.")
if self_root != init_root:
grains["virtual_subtype"] = "chroot"
except (IOError, OSError):
pass
if isdir("/proc/vz"):
if os.path.isfile("/proc/vz/version"):
grains["virtual"] = "openvzhn"
elif os.path.isfile("/proc/vz/veinfo"):
grains["virtual"] = "openvzve"
# a posteriori, it's expected for these to have failed:
failed_commands.discard("lspci")
failed_commands.discard("dmidecode")
if os.path.isfile("/proc/self/status"):
with salt.utils.files.fopen("/proc/self/status") as status_file:
vz_re = re.compile(r"^envID:\s+(\d+)$")
for line in status_file:
vz_match = vz_re.match(line.rstrip("\n"))
if vz_match and int(vz_match.groups()[0]) != 0:
grains["virtual"] = "openvzve"
elif vz_match and int(vz_match.groups()[0]) == 0:
grains["virtual"] = "openvzhn"
if isdir("/proc/sys/xen") or isdir("/sys/bus/xen") or isdir("/proc/xen"):
if os.path.isfile("/proc/xen/xsd_kva"):
grains["virtual_subtype"] = "Xen Dom0"
else:
if osdata.get("productname", "") == "HVM domU":
grains["virtual_subtype"] = "Xen HVM DomU"
elif os.path.isfile("/proc/xen/capabilities") and os.access(
"/proc/xen/capabilities", os.R_OK
):
with salt.utils.files.fopen("/proc/xen/capabilities") as fhr:
if "control_d" not in fhr.read():
grains["virtual_subtype"] = "Xen PV DomU"
else:
grains["virtual_subtype"] = "Xen Dom0"
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir("/sys/bus/xen"):
if "xen:" in __salt__["cmd.run"]("dmesg").lower():
grains["virtual_subtype"] = "Xen PV DomU"
elif os.path.isfile("/sys/bus/xen/drivers/xenconsole"):
# An actual DomU will have the xenconsole driver
grains["virtual_subtype"] = "Xen PV DomU"
# If a Dom0 or DomU was detected, obviously this is xen
if "dom" in grains.get("virtual_subtype", "").lower():
grains["virtual"] = "xen"
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile("/proc/1/cgroup"):
try:
with salt.utils.files.fopen("/proc/1/cgroup", "r") as fhr:
fhr_contents = fhr.read()
if ":/lxc/" in fhr_contents:
grains["virtual"] = "container"
grains["virtual_subtype"] = "LXC"
elif ":/kubepods/" in fhr_contents:
grains["virtual_subtype"] = "kubernetes"
elif ":/libpod_parent/" in fhr_contents:
grains["virtual_subtype"] = "libpod"
else:
if any(
x in fhr_contents
for x in (":/system.slice/docker", ":/docker/", ":/docker-ce/")
):
grains["virtual"] = "container"
grains["virtual_subtype"] = "Docker"
except IOError:
pass
if os.path.isfile("/proc/cpuinfo"):
with salt.utils.files.fopen("/proc/cpuinfo", "r") as fhr:
if "QEMU Virtual CPU" in fhr.read():
grains["virtual"] = "kvm"
if os.path.isfile("/sys/devices/virtual/dmi/id/product_name"):
try:
with salt.utils.files.fopen(
"/sys/devices/virtual/dmi/id/product_name", "r"
) as fhr:
output = salt.utils.stringutils.to_unicode(
fhr.read(), errors="replace"
)
if "VirtualBox" in output:
grains["virtual"] = "VirtualBox"
elif "RHEV Hypervisor" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
elif "oVirt Node" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "ovirt"
elif "Google" in output:
grains["virtual"] = "gce"
elif "BHYVE" in output:
grains["virtual"] = "bhyve"
except UnicodeDecodeError:
# Some firmwares provide non-valid 'product_name'
# files, ignore them
log.debug(
"The content in /sys/devices/virtual/dmi/id/product_name is not valid"
)
except IOError:
pass
elif osdata["kernel"] == "FreeBSD":
kenv = salt.utils.path.which("kenv")
if kenv:
product = __salt__["cmd.run"]("{0} smbios.system.product".format(kenv))
maker = __salt__["cmd.run"]("{0} smbios.system.maker".format(kenv))
if product.startswith("VMware"):
grains["virtual"] = "VMware"
if product.startswith("VirtualBox"):
grains["virtual"] = "VirtualBox"
if maker.startswith("Xen"):
grains["virtual_subtype"] = "{0} {1}".format(maker, product)
grains["virtual"] = "xen"
if maker.startswith("Microsoft") and product.startswith("Virtual"):
grains["virtual"] = "VirtualPC"
if maker.startswith("OpenStack"):
grains["virtual"] = "OpenStack"
if maker.startswith("Bochs"):
grains["virtual"] = "kvm"
if sysctl:
hv_vendor = __salt__["cmd.run"]("{0} -n hw.hv_vendor".format(sysctl))
model = __salt__["cmd.run"]("{0} -n hw.model".format(sysctl))
jail = __salt__["cmd.run"]("{0} -n security.jail.jailed".format(sysctl))
if "bhyve" in hv_vendor:
grains["virtual"] = "bhyve"
elif "QEMU Virtual CPU" in model:
grains["virtual"] = "kvm"
if jail == "1":
grains["virtual_subtype"] = "jail"
elif osdata["kernel"] == "OpenBSD":
if "manufacturer" in osdata:
if osdata["manufacturer"] in ["QEMU", "Red Hat", "Joyent"]:
grains["virtual"] = "kvm"
if osdata["manufacturer"] == "OpenBSD":
grains["virtual"] = "vmm"
elif osdata["kernel"] == "NetBSD":
if sysctl:
if "QEMU Virtual CPU" in __salt__["cmd.run"](
"{0} -n machdep.cpu_brand".format(sysctl)
):
grains["virtual"] = "kvm"
elif "invalid" not in __salt__["cmd.run"](
"{0} -n machdep.xen.suspend".format(sysctl)
):
grains["virtual"] = "Xen PV DomU"
elif "VMware" in __salt__["cmd.run"](
"{0} -n machdep.dmi.system-vendor".format(sysctl)
):
grains["virtual"] = "VMware"
# NetBSD has Xen dom0 support
elif (
__salt__["cmd.run"]("{0} -n machdep.idle-mechanism".format(sysctl))
== "xen"
):
if os.path.isfile("/var/run/xenconsoled.pid"):
grains["virtual_subtype"] = "Xen Dom0"
elif osdata["kernel"] == "SunOS":
# we did not get any data from virtinfo or prtdiag
# check the zonename here as fallback
zonename = salt.utils.path.which("zonename")
if zonename:
zone = __salt__["cmd.run"]("{0}".format(zonename))
if zone != "global":
grains["virtual"] = "zone"
# last ditch efford to check the brand identifier
elif os.path.isdir("/.SUNWnative"):
grains["virtual"] = "zone"
# If we have a virtual_subtype, we're virtual, but maybe we couldn't
# figure out what specific virtual type we were?
if grains.get("virtual_subtype") and grains["virtual"] == "physical":
grains["virtual"] = "virtual"
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
"cannot execute it. Grains output might not be "
"accurate.",
command,
)
return grains
def _virtual_hv(osdata):
grains = {}
# Bail early if we're not running on Xen
try:
if "xen" not in osdata["virtual"]:
return grains
except KeyError:
return grains
try:
version = {}
for fn in ("major", "minor", "extra"):
with salt.utils.files.fopen(
"/sys/hypervisor/version/{}".format(fn), "r"
) as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains["virtual_hv_version"] = "{}.{}{}".format(
version["major"], version["minor"], version["extra"]
)
grains["virtual_hv_version_info"] = [
version["major"],
version["minor"],
version["extra"],
]
except (IOError, OSError, KeyError):
pass
xen_feature_table = {
0: "writable_page_tables",
1: "writable_descriptor_tables",
2: "auto_translated_physmap",
3: "supervisor_mode_kernel",
4: "pae_pgdir_above_4gb",
5: "mmu_pt_update_preserve_ad",
7: "gnttab_map_avail_bits",
8: "hvm_callback_vector",
9: "hvm_safe_pvclock",
10: "hvm_pirqs",
11: "dom0",
12: "grant_map_identity",
13: "memory_op_vnode_supported",
14: "ARM_SMCCC_supported",
}
try:
with salt.utils.files.fopen("/sys/hypervisor/properties/features", "r") as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains["virtual_hv_features"] = features
grains["virtual_hv_features_list"] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
grains = {}
bsd_choices = ("FreeBSD", "NetBSD", "OpenBSD", "MacOS")
if osdata["os"] in bsd_choices:
grains["ps"] = "ps auxwww"
elif osdata["os_family"] == "Solaris":
grains["ps"] = "/usr/ucb/ps auxwww"
elif osdata["os"] == "Windows":
grains["ps"] = "tasklist.exe"
elif osdata.get("virtual", "") == "openvzhn":
grains["ps"] = (
'ps -fH -p $(grep -l "^envID:[[:space:]]*0\\$" '
'/proc/[0-9]*/status | sed -e "s=/proc/\\([0-9]*\\)/.*=\\1=") '
"| awk '{ $7=\"\"; print }'"
)
elif osdata["os_family"] == "AIX":
grains["ps"] = "/usr/bin/ps auxww"
elif osdata["os_family"] == "NILinuxRT":
grains["ps"] = "ps -o user,pid,ppid,tty,time,comm"
else:
grains["ps"] = "ps -efHww"
return grains
def _clean_value(key, val):
if val is None or not val or re.match("none", val, flags=re.IGNORECASE):
return None
elif "uuid" in key:
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace("HW %s value %s is an invalid UUID", key, val.replace("\n", " "))
return None
elif re.search("serial|part|version", key):
# 'To be filled by O.E.M.
if (
re.match(r"^[0]+$", val)
or re.match(r"[0]?1234567[8]?[9]?[0]?", val)
or re.search(
r"sernum|part[_-]?number|specified|filled|applicable",
val,
flags=re.IGNORECASE,
)
):
return None
elif re.search("asset|manufacturer", key):
if re.search(
r"manufacturer|to be filled|available|asset|^no(ne|t)",
val,
flags=re.IGNORECASE,
):
return None
else:
if re.search(r"to be filled", val, flags=re.IGNORECASE) or re.search(
r"un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)",
val,
flags=re.IGNORECASE,
):
return None
return val
def _windows_os_release_grain(caption, product_type):
version = "Unknown"
release = ""
if "Server" in caption:
if re.match(r"^Microsoft Hyper-V Server$", caption):
version = "2019"
else:
for item in caption.split(" "):
# If it's all digits, then it's version
if re.match(r"\d+", item):
version = item
# If it starts with R and then numbers, it's the release
if re.match(r"^R\d+$", item):
release = item
os_release = "{0}Server{1}".format(version, release)
else:
for item in caption.split(" "):
if re.match(r"^(\d+(\.\d+)?)|Thin|Vista|XP$", item):
version = item
os_release = version
if os_release in ["Unknown"]:
os_release = platform.release()
server = {
"Vista": "2008Server",
"7": "2008ServerR2",
"8": "2012Server",
"8.1": "2012ServerR2",
"10": "2016Server",
}
up the actual Server Release.
# (Product Type 1 is Desktop, Everything else is Server)
if product_type > 1 and os_release in server:
os_release = server[os_release]
return os_release
def _windows_platform_data():
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {"product": None, "serial": None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard["product"] = motherboardinfo.Product
motherboard["serial"] = motherboardinfo.SerialNumber
except IndexError:
log.debug("Motherboard info not available on this system")
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info["ServicePackMajor"] > 0:
service_pack = "".join(["SP", six.text_type(info["ServicePackMajor"])])
os_release = _windows_os_release_grain(
caption=osinfo.Caption, product_type=osinfo.ProductType
)
grains = {
"kernelrelease": _clean_value("kernelrelease", osinfo.Version),
"kernelversion": _clean_value("kernelversion", kernel_version),
"osversion": _clean_value("osversion", osinfo.Version),
"osrelease": _clean_value("osrelease", os_release),
"osservicepack": _clean_value("osservicepack", service_pack),
"osmanufacturer": _clean_value("osmanufacturer", osinfo.Manufacturer),
"manufacturer": _clean_value("manufacturer", systeminfo.Manufacturer),
"productname": _clean_value("productname", systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
"biosversion": _clean_value("biosversion", biosinfo.Name.strip()),
"serialnumber": _clean_value("serialnumber", biosinfo.SerialNumber),
"osfullname": _clean_value("osfullname", osinfo.Caption),
"timezone": _clean_value("timezone", timeinfo.Description),
"windowsdomain": _clean_value("windowsdomain", net_info["Domain"]),
"windowsdomaintype": _clean_value(
"windowsdomaintype", net_info["DomainType"]
),
"motherboard": {
"productname": _clean_value(
"motherboard.productname", motherboard["product"]
),
"serialnumber": _clean_value(
"motherboard.serialnumber", motherboard["serial"]
),
},
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if "VRTUAL" in biosinfo.Version: # (not a typo)
grains["virtual"] = "HyperV"
elif "A M I" in biosinfo.Version:
grains["virtual"] = "VirtualPC"
elif "VMware" in systeminfo.Model:
grains["virtual"] = "VMware"
elif "VirtualBox" in systeminfo.Model:
grains["virtual"] = "VirtualBox"
elif "Xen" in biosinfo.Version:
grains["virtual"] = "Xen"
if "HVM domU" in systeminfo.Model:
grains["virtual_subtype"] = "HVM domU"
elif "OpenStack" in systeminfo.Model:
grains["virtual"] = "OpenStack"
elif "AMAZON" in biosinfo.Version:
grains["virtual"] = "EC2"
return grains
def _osx_platform_data():
cmd = "system_profiler SPHardwareDataType"
hardware = __salt__["cmd.run"](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(": ")
if field_name.strip() == "Model Name":
key = "model_name"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = "boot_rom_version"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = "smc_version"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = "system_serialnumber"
grains[key] = _clean_value(key, field_val)
return grains
def id_():
return {"id": __opts__.get("id", "")}
_REPLACE_LINUX_RE = re.compile(r"\W(?:gnu/)?linux", re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
"redhatente": "RedHat",
"gentoobase": "Gentoo",
"archarm": "Arch ARM",
"arch": "Arch",
"debian": "Debian",
"raspbian": "Raspbian",
"fedoraremi": "Fedora",
"chapeau": "Chapeau",
"korora": "Korora",
"amazonami": "Amazon",
"alt": "ALT",
"enterprise": "OEL",
"oracleserv": "OEL",
"cloudserve": "CloudLinux",
"cloudlinux": "CloudLinux",
"pidora": "Fedora",
"scientific": "ScientificLinux",
"synology": "Synology",
"nilrt": "NILinuxRT",
"poky": "Poky",
"manjaro": "Manjaro",
"manjarolin": "Manjaro",
"univention": "Univention",
"antergos": "Antergos",
"sles": "SUSE",
"void": "Void",
"slesexpand": "RES",
"linuxmint": "Mint",
"neon": "KDE neon",
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
"Ubuntu": "Debian",
"Fedora": "RedHat",
"Chapeau": "RedHat",
"Korora": "RedHat",
"FedBerry": "RedHat",
"CentOS": "RedHat",
"GoOSe": "RedHat",
"Scientific": "RedHat",
"Amazon": "RedHat",
"CloudLinux": "RedHat",
"OVS": "RedHat",
"OEL": "RedHat",
"XCP": "RedHat",
"XCP-ng": "RedHat",
"XenServer": "RedHat",
"RES": "RedHat",
"Sangoma": "RedHat",
"Mandrake": "Mandriva",
"ESXi": "VMware",
"Mint": "Debian",
"VMwareESX": "VMware",
"Bluewhite64": "Bluewhite",
"Slamd64": "Slackware",
"SLES": "Suse",
"SUSE Enterprise Server": "Suse",
"SUSE Enterprise Server": "Suse",
"SLED": "Suse",
"openSUSE": "Suse",
"SUSE": "Suse",
"openSUSE Leap": "Suse",
"openSUSE Tumbleweed": "Suse",
"SLES_SAP": "Suse",
"Solaris": "Solaris",
"SmartOS": "Solaris",
"OmniOS": "Solaris",
"OpenIndiana Development": "Solaris",
"OpenIndiana": "Solaris",
"OpenSolaris Development": "Solaris",
"OpenSolaris": "Solaris",
"Oracle Solaris": "Solaris",
"Arch ARM": "Arch",
"Manjaro": "Arch",
"Antergos": "Arch",
"ALT": "RedHat",
"Trisquel": "Debian",
"GCEL": "Debian",
"Linaro": "Debian",
"elementary OS": "Debian",
"elementary": "Debian",
"Univention": "Debian",
"ScientificLinux": "RedHat",
"Raspbian": "Debian",
"Devuan": "Debian",
"antiX": "Debian",
"Kali": "Debian",
"neon": "Debian",
"Cumulus": "Debian",
"Deepin": "Debian",
"NILinuxRT": "NILinuxRT",
"KDE neon": "Debian",
"Void": "Void",
"IDMS": "Debian",
"Funtoo": "Gentoo",
"AIX": "AIX",
"TurnKey": "Debian",
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile(
(
"^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:'|\")?"
"([\\w\\s\\.\\-_]+)(?:'|\")?"
)
)
def _linux_bin_exists(binary):
for search_cmd in ("which", "type -ap"):
try:
return __salt__["cmd.retcode"]("{0} {1}".format(search_cmd, binary)) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return (
len(
__salt__["cmd.run_all"]("whereis -b {0}".format(binary))[
"stdout"
].split()
)
> 1
)
except salt.exceptions.CommandExecutionError:
return False
def _parse_lsb_release():
ret = {}
try:
log.trace("Attempting to parse /etc/lsb-release")
with salt.utils.files.fopen("/etc/lsb-release") as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip("\n")).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret["lsb_{0}".format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace("Failed to parse /etc/lsb-release: %s", exc)
return ret
def _parse_os_release(*os_release_files):
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile("^([\\w]+)=(?:'|\")?(.*?)(?:'|\")?$")
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r"\1", match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
part = {
"o": "operating system",
"h": "hardware",
"a": "application",
}
ret = {}
cpe = (cpe or "").split(":")
if len(cpe) > 4 and cpe[0] == "cpe":
if cpe[1].startswith("/"): # WFN to URI
ret["vendor"], ret["product"], ret["version"] = cpe[2:5]
ret["phase"] = cpe[5] if len(cpe) > 5 else None
ret["part"] = part.get(cpe[1][1:])
elif len(cpe) == 6 and cpe[1] == "2.3": # WFN to a string
ret["vendor"], ret["product"], ret["version"] = [
x if x != "*" else None for x in cpe[3:6]
]
ret["phase"] = None
ret["part"] = part.get(cpe[2])
elif len(cpe) > 7 and len(cpe) <= 13 and cpe[1] == "2.3": # WFN to a string
ret["vendor"], ret["product"], ret["version"], ret["phase"] = [
x if x != "*" else None for x in cpe[3:7]
]
ret["part"] = part.get(cpe[2])
return ret
def os_data():
grains = {
"num_gpus": 0,
"gpus": [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(
grains["kernel"],
grains["nodename"],
grains["kernelrelease"],
grains["kernelversion"],
grains["cpuarch"],
_,
) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains["kernel"] = "proxy"
grains["kernelrelease"] = "proxy"
grains["kernelversion"] = "proxy"
grains["osrelease"] = "proxy"
grains["os"] = "proxy"
grains["os_family"] = "proxy"
grains["osfullname"] = "proxy"
elif salt.utils.platform.is_windows():
grains["os"] = "Windows"
grains["os_family"] = "Windows"
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if "Server" in grains["osrelease"]:
osrelease_info = grains["osrelease"].split("Server", 1)
osrelease_info[1] = osrelease_info[1].lstrip("R")
else:
osrelease_info = grains["osrelease"].split(".")
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains["osrelease_info"] = tuple(osrelease_info)
grains["osfinger"] = "{os}-{ver}".format(
os=grains["os"], ver=grains["osrelease"]
)
grains["init"] = "Windows"
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists("selinuxenabled"):
log.trace("Adding selinux grains")
grains["selinux"] = {}
grains["selinux"]["enabled"] = (
__salt__["cmd.retcode"]("selinuxenabled") == 0
)
if _linux_bin_exists("getenforce"):
grains["selinux"]["enforced"] = __salt__["cmd.run"](
"getenforce"
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists("systemctl") and _linux_bin_exists("localectl"):
log.trace("Adding systemd grains")
grains["systemd"] = {}
systemd_info = __salt__["cmd.run"]("systemctl --version").splitlines()
grains["systemd"]["version"] = systemd_info[0].split()[1]
grains["systemd"]["features"] = systemd_info[1]
# Add init grain
grains["init"] = "unknown"
log.trace("Adding init grain")
try:
os.stat("/run/systemd/system")
grains["init"] = "systemd"
except (OSError, IOError):
try:
with salt.utils.files.fopen("/proc/1/cmdline") as fhr:
init_cmdline = fhr.read().replace("\x00", " ").split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning("Unable to fetch data from /proc/1/cmdline")
if init_bin is not None and init_bin.endswith("bin/init"):
supported_inits = (b"upstart", b"sysvinit", b"systemd")
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__["file_buffer_size"]
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, "rb") as fp_:
edge = b""
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode("utf-8")
grains["init"] = item
buf = b""
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
"Unable to read from init_bin (%s): %s", init_bin, exc
)
elif salt.utils.path.which("supervisord") in init_cmdline:
grains["init"] = "supervisord"
elif salt.utils.path.which("dumb-init") in init_cmdline:
# https://github.com/Yelp/dumb-init
grains["init"] = "dumb-init"
elif salt.utils.path.which("tini") in init_cmdline:
# https://github.com/krallin/tini
grains["init"] = "tini"
elif init_cmdline == ["runit"]:
grains["init"] = "runit"
elif "/sbin/my_init" in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains["init"] = "runit"
else:
log.debug(
"Could not determine init system from command line: (%s)",
" ".join(init_cmdline),
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace("Getting lsb_release distro information")
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = "lsb_{0}{1}".format(
"" if key.startswith("distrib_") else "distrib_", key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace("lsb_release python bindings not available")
grains.update(_parse_lsb_release())
if grains.get("lsb_distrib_description", "").lower().startswith("antergos"):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains["osfullname"] = "Antergos Linux"
elif "lsb_distrib_id" not in grains:
log.trace("Failed to get lsb_distrib_id, trying to parse os-release")
os_release = _parse_os_release("/etc/os-release", "/usr/lib/os-release")
if os_release:
if "NAME" in os_release:
grains["lsb_distrib_id"] = os_release["NAME"].strip()
if "VERSION_ID" in os_release:
grains["lsb_distrib_release"] = os_release["VERSION_ID"]
if "VERSION_CODENAME" in os_release:
grains["lsb_distrib_codename"] = os_release["VERSION_CODENAME"]
elif "PRETTY_NAME" in os_release:
codename = os_release["PRETTY_NAME"]
# https://github.com/saltstack/salt/issues/44108
if os_release["ID"] == "debian":
codename_match = re.search(r"\((\w+)\)$", codename)
if codename_match:
codename = codename_match.group(1)
grains["lsb_distrib_codename"] = codename
if "CPE_NAME" in os_release:
cpe = _parse_cpe_name(os_release["CPE_NAME"])
if not cpe:
log.error("Broken CPE_NAME format in /etc/os-release!")
elif cpe.get("vendor", "").lower() in ["suse", "opensuse"]:
grains["os"] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains["osfullname"] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains["osfullname"] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if (
cpe.get("version") and cpe.get("vendor") == "opensuse"
): # Keep VERSION_ID for SLES
grains["lsb_distrib_release"] = cpe["version"]
elif os.path.isfile("/etc/SuSE-release"):
log.trace("Parsing distrib info from /etc/SuSE-release")
grains["lsb_distrib_id"] = "SUSE"
version = ""
patch = ""
with salt.utils.files.fopen("/etc/SuSE-release") as fhr:
for line in fhr:
if "enterprise" in line.lower():
grains["lsb_distrib_id"] = "SLES"
grains["lsb_distrib_codename"] = re.sub(
r"\(.+\)", "", line
).strip()
elif "version" in line.lower():
version = re.sub(r"[^0-9]", "", line)
elif "patchlevel" in line.lower():
patch = re.sub(r"[^0-9]", "", line)
grains["lsb_distrib_release"] = version
if patch:
grains["lsb_distrib_release"] += "." + patch
patchstr = "SP" + patch
if (
grains["lsb_distrib_codename"]
and patchstr not in grains["lsb_distrib_codename"]
):
grains["lsb_distrib_codename"] += " " + patchstr
if not grains.get("lsb_distrib_codename"):
grains["lsb_distrib_codename"] = "n.a"
elif os.path.isfile("/etc/altlinux-release"):
log.trace("Parsing distrib info from /etc/altlinux-release")
# ALT Linux
grains["lsb_distrib_id"] = "altlinux"
with salt.utils.files.fopen("/etc/altlinux-release") as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == "ALT":
grains["lsb_distrib_release"] = comps[2]
grains["lsb_distrib_codename"] = (
comps[3].replace("(", "").replace(")", "")
)
elif os.path.isfile("/etc/centos-release"):
log.trace("Parsing distrib info from /etc/centos-release")
# CentOS Linux
grains["lsb_distrib_id"] = "CentOS"
with salt.utils.files.fopen("/etc/centos-release") as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r"\d+\.\d+")
find_codename = re.compile(r"(?<=\()(.*?)(?=\))")
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains["lsb_distrib_release"] = release.group()
if codename is not None:
grains["lsb_distrib_codename"] = codename.group()
elif os.path.isfile("/etc.defaults/VERSION") and os.path.isfile(
"/etc.defaults/synoinfo.conf"
):
grains["osfullname"] = "Synology"
log.trace(
"Parsing Synology distrib info from /etc/.defaults/VERSION"
)
with salt.utils.files.fopen("/etc.defaults/VERSION", "r") as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip("\n").split("=")
except ValueError:
continue
if key in ("majorversion", "minorversion", "buildnumber"):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
"Unable to determine Synology version info. "
"Please report this, as it is likely a bug."
)
else:
grains[
"osrelease"
] = "{majorversion}.{minorversion}-{buildnumber}".format(
**synoinfo
)
log.trace(
"Getting OS name, release, and codename from distro id, version, codename"
)
(osname, osrelease, oscodename) = [
x.strip('"').strip("'") for x in _linux_distribution()
]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if "osfullname" not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get("lsb_distrib_id", "").lower().startswith("nilrt"):
grains["osfullname"] = "nilrt"
else:
grains["osfullname"] = grains.get("lsb_distrib_id", osname).strip()
if "osrelease" not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
# This also affects Centos 8
if any(
os in grains.get("lsb_distrib_codename", "")
for os in ["CentOS Linux 7", "CentOS Linux 8"]
):
grains.pop("lsb_distrib_release", None)
grains["osrelease"] = grains.get("lsb_distrib_release", osrelease).strip()
grains["oscodename"] = (
grains.get("lsb_distrib_codename", "").strip() or oscodename
)
if "Red Hat" in grains["oscodename"]:
grains["oscodename"] = oscodename
distroname = _REPLACE_LINUX_RE.sub("", grains["osfullname"]).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(" ", "").lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if "os" not in grains:
grains["os"] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains["kernel"] == "SunOS":
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index("_") + 1 :]
grains["os"] = grains["osfullname"] = "SmartOS"
# store a parsed version of YYYY.MM.DD as osrelease
grains["osrelease"] = ".".join(
[
uname_v.split("T")[0][0:4],
uname_v.split("T")[0][4:6],
uname_v.split("T")[0][6:8],
]
)
# store a untouched copy of the timestamp in osrelease_stamp
grains["osrelease_stamp"] = uname_v
elif os.path.isfile("/etc/release"):
with salt.utils.files.fopen("/etc/release", "r") as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r"((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?"
r"\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?"
)
(
osname,
development,
osmajorrelease,
osminorrelease,
) = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains["os"] = grains["osfullname"] = "Solaris"
grains["osrelease"] = ""
else:
if development is not None:
osname = " ".join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains["os"] = grains["osfullname"] = osname
if osname in ["Oracle Solaris"] and uname_v.startswith(
osmajorrelease
):
# Oracla Solars 11 and up have minor version in uname
grains["osrelease"] = uname_v
elif osname in ["OmniOS"]:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains["osrelease"] = ".".join(osrelease)
grains["osrelease_stamp"] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains["osrelease"] = ".".join(osrelease)
grains["osrelease_stamp"] = uname_v
grains.update(_sunos_cpudata())
elif grains["kernel"] == "VMkernel":
grains["os"] = "ESXi"
elif grains["kernel"] == "Darwin":
osrelease = __salt__["cmd.run"]("sw_vers -productVersion")
osname = __salt__["cmd.run"]("sw_vers -productName")
osbuild = __salt__["cmd.run"]("sw_vers -buildVersion")
grains["os"] = "MacOS"
grains["os_family"] = "MacOS"
grains["osfullname"] = "{0} {1}".format(osname, osrelease)
grains["osrelease"] = osrelease
grains["osbuild"] = osbuild
grains["init"] = "launchd"
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains["kernel"] == "AIX":
osrelease = __salt__["cmd.run"]("oslevel")
osrelease_techlevel = __salt__["cmd.run"]("oslevel -r")
osname = __salt__["cmd.run"]("uname")
grains["os"] = "AIX"
grains["osfullname"] = osname
grains["osrelease"] = osrelease
grains["osrelease_techlevel"] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains["os"] = grains["kernel"]
if grains["kernel"] == "FreeBSD":
grains["osfullname"] = grains["os"]
try:
grains["osrelease"] = __salt__["cmd.run"]("freebsd-version -u").split("-")[
0
]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains["osrelease"] = grains["kernelrelease"].split("-")[0]
grains.update(_bsd_cpudata(grains))
if grains["kernel"] in ("OpenBSD", "NetBSD"):
grains.update(_bsd_cpudata(grains))
grains["osrelease"] = grains["kernelrelease"].split("-")[0]
if grains["kernel"] == "NetBSD":
grains.update(_netbsd_gpu_data())
if not grains["os"]:
grains["os"] = "Unknown {0}".format(grains["kernel"])
grains["os_family"] = "Unknown"
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains["os_family"] = _OS_FAMILY_MAP.get(grains["os"], grains["os"])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get("os_family") == "Debian":
osarch = __salt__["cmd.run"]("dpkg --print-architecture").strip()
elif grains.get("os_family") in ["RedHat", "Suse"]:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get("os_family") in ("NILinuxRT", "Poky"):
archinfo = {}
for line in __salt__["cmd.run"]("opkg print-architecture").splitlines():
if line.startswith("arch"):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains["cpuarch"]
grains["osarch"] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get("osrelease", ""):
osrelease_info = grains["osrelease"].split(".")
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains["osrelease_info"] = tuple(osrelease_info)
try:
grains["osmajorrelease"] = int(grains["osrelease_info"][0])
except (IndexError, TypeError, ValueError):
log.debug(
"Unable to derive osmajorrelease from osrelease_info '%s'. "
"The osmajorrelease grain will not be set.",
grains["osrelease_info"],
)
os_name = grains[
"os"
if grains.get("os")
in ("Debian", "FreeBSD", "OpenBSD", "NetBSD", "Mac", "Raspbian")
else "osfullname"
]
grains["osfinger"] = "{0}-{1}".format(
os_name,
grains["osrelease"]
if os_name in ("Ubuntu",)
else grains["osrelease_info"][0],
)
return grains
def locale_info():
grains = {}
grains["locale_info"] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains["locale_info"]["defaultlanguage"],
grains["locale_info"]["defaultencoding"],
) = locale.getdefaultlocale()
except Exception: # pylint: disable=broad-except
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains["locale_info"]["defaultlanguage"] = "unknown"
grains["locale_info"]["defaultencoding"] = "unknown"
grains["locale_info"]["detectedencoding"] = __salt_system_encoding__
grains["locale_info"]["timezone"] = "unknown"
if _DATEUTIL_TZ:
try:
grains["locale_info"]["timezone"] = datetime.datetime.now(
dateutil.tz.tzlocal()
).tzname()
except UnicodeDecodeError:
# Because the method 'tzname' is not a part of salt the decoding error cant be fixed.
# The error is in datetime in the python2 lib
if salt.utils.platform.is_windows():
grains["locale_info"]["timezone"] = time.tzname[0].decode("mbcs")
return grains
def hostname():
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains["localhost"] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error(
"Having trouble getting a hostname. Does this machine have its hostname and domain set properly?"
)
__FQDN__ = "localhost.localdomain"
grains["fqdn"] = __FQDN__
(grains["host"], grains["domain"]) = grains["fqdn"].partition(".")[::2]
return grains
def append_domain():
grain = {}
if salt.utils.platform.is_proxy():
return grain
if "append_domain" in __opts__:
grain["append_domain"] = __opts__["append_domain"]
return grain
def fqdns():
# Provides:
# fqdns
opt = {"fqdns": []}
if __opts__.get(
"enable_fqdns_grains",
False
if salt.utils.platform.is_windows() or salt.utils.platform.is_proxy()
else True,
):
opt = __salt__["network.fqdns"]()
return opt
def ip_fqdn():
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret["ipv4"] = salt.utils.network.ip_addrs(include_loopback=True)
ret["ipv6"] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()["fqdn"]
for socket_type, ipv_num in ((socket.AF_INET, "4"), (socket.AF_INET6, "6")):
key = "fqdn_ip" + ipv_num
if not ret["ipv" + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except (socket.error, UnicodeError):
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__["__role"] == "master":
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
"second timeout when rendering grains. Set the dns or "
"/etc/hosts for IPv%s to clear this.",
ipv_num,
_fqdn,
timediff,
ipv_num,
)
ret[key] = []
return ret
def ip_interfaces():
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet", []):
if "address" in inet:
iface_ips.append(inet["address"])
for inet in ifaces[face].get("inet6", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip_interfaces": ret}
def ip4_interfaces():
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip4_interfaces": ret}
def ip6_interfaces():
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet6", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip6_interfaces": ret}
def hwaddr_interfaces():
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if "hwaddr" in ifaces[face]:
ret[face] = ifaces[face]["hwaddr"]
return {"hwaddr_interfaces": ret}
def dns():
# Provides:
# dns
if salt.utils.platform.is_windows() or "proxyminion" in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ("nameservers", "ip4_nameservers", "ip6_nameservers", "sortlist"):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {"dns": resolv} if resolv else {}
def get_machine_id():
# Provides:
# machine-id
if platform.system() == "AIX":
return _aix_get_machine_id()
locations = ["/etc/machine-id", "/var/lib/dbus/machine-id"]
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {"machine_id": machineid.read().strip()}
def cwd():
return {"cwd": os.getcwd()}
def path():
# Provides:
# path
# systempath
_path = salt.utils.stringutils.to_unicode(os.environ.get("PATH", "").strip())
return {
"path": _path,
"systempath": _path.split(os.path.pathsep),
}
def pythonversion():
# Provides:
# pythonversion
return {"pythonversion": list(sys.version_info)}
def pythonpath():
# Provides:
# pythonpath
return {"pythonpath": sys.path}
def pythonexecutable():
# Provides:
# pythonexecutable
return {"pythonexecutable": sys.executable}
def saltpath():
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {"saltpath": os.path.dirname(salt_path)}
def saltversion():
# Provides:
# saltversion
from salt.version import __version__
return {"saltversion": __version__}
def zmqversion():
# Provides:
# zmqversion
try:
import zmq
return {"zmqversion": zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {"saltversioninfo": list(__version_info__)}
def _hw_data(osdata):
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata["kernel"] == "Linux" and os.path.exists("/sys/class/dmi/id"):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
"biosversion": "bios_version",
"productname": "product_name",
"manufacturer": "sys_vendor",
"biosreleasedate": "bios_date",
"uuid": "product_uuid",
"serialnumber": "product_serial",
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join("/sys/class/dmi/id", fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, "r") as ifile:
grains[key] = salt.utils.stringutils.to_unicode(
ifile.read().strip(), errors="replace"
)
if key == "uuid":
grains["uuid"] = grains["uuid"].lower()
except UnicodeDecodeError:
# Some firmwares provide non-valid 'product_name'
# files, ignore them
log.debug(
"The content in /sys/devices/virtual/dmi/id/product_name is not valid"
)
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(["dmidecode", "smbios"]) is not None and not (
salt.utils.platform.is_smartos()
or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata["kernel"] == "SunOS" and osdata["cpuarch"].startswith("sparc")
)
):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
"biosversion": __salt__["smbios.get"]("bios-version"),
"productname": __salt__["smbios.get"]("system-product-name"),
"manufacturer": __salt__["smbios.get"]("system-manufacturer"),
"biosreleasedate": __salt__["smbios.get"]("bios-release-date"),
"uuid": __salt__["smbios.get"]("system-uuid"),
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__["smbios.get"]("system-uuid")
if uuid is not None:
grains["uuid"] = uuid.lower()
for serial in (
"system-serial-number",
"chassis-serial-number",
"baseboard-serial-number",
):
serial = __salt__["smbios.get"](serial)
if serial is not None:
grains["serialnumber"] = serial
break
elif salt.utils.path.which_bin(["fw_printenv"]) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
"manufacturer": "manufacturer",
"serialnumber": "serial
"productname": "DeviceDesc",
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__["cmd.run_all"]("fw_printenv {0}".format(cmd_key))
if result["retcode"] == 0:
uboot_keyval = result["stdout"].split("=")
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata["kernel"] == "FreeBSD":
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which("kenv")
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
"biosversion": "smbios.bios.version",
"manufacturer": "smbios.system.maker",
"serialnumber": "smbios.system.serial",
"productname": "smbios.system.product",
"biosreleasedate": "smbios.bios.reldate",
"uuid": "smbios.system.uuid",
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__["cmd.run"]("{0} {1}".format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "OpenBSD":
sysctl = salt.utils.path.which("sysctl")
hwdata = {
"biosversion": "hw.version",
"manufacturer": "hw.vendor",
"productname": "hw.product",
"serialnumber": "hw.serialno",
"uuid": "hw.uuid",
}
for key, oid in six.iteritems(hwdata):
value = __salt__["cmd.run"]("{0} -n {1}".format(sysctl, oid))
if not value.endswith(" value is not available"):
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "NetBSD":
sysctl = salt.utils.path.which("sysctl")
nbsd_hwdata = {
"biosversion": "machdep.dmi.board-version",
"manufacturer": "machdep.dmi.system-vendor",
"serialnumber": "machdep.dmi.system-serial",
"productname": "machdep.dmi.system-product",
"biosreleasedate": "machdep.dmi.bios-date",
"uuid": "machdep.dmi.system-uuid",
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__["cmd.run_all"]("{0} -n {1}".format(sysctl, oid))
if result["retcode"] == 0:
grains[key] = _clean_value(key, result["stdout"])
elif osdata["kernel"] == "Darwin":
grains["manufacturer"] = "Apple Inc."
sysctl = salt.utils.path.which("sysctl")
hwdata = {"productname": "hw.model"}
for key, oid in hwdata.items():
value = __salt__["cmd.run"]("{0} -b {1}".format(sysctl, oid))
if not value.endswith(" is invalid"):
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "SunOS" and osdata["cpuarch"].startswith("sparc"):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (
("/usr/sbin/prtdiag", "-v"),
("/usr/sbin/prtconf", "-vp"),
("/usr/sbin/virtinfo", "-a"),
):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__["cmd.run"]("{0} {1}".format(cmd, args))
data += "\n"
sn_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)", # prtdiag
r"(?im)^\s*chassis-sn:\s*(\S+)", # prtconf
r"(?im)^\s*Chassis\s+Serial
]
]
obp_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)", # prtdiag
r"(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)", # prtconf
]
]
fw_regexes = [
re.compile(r)
for r in [r"(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)"] # prtdiag
]
uuid_regexes = [
re.compile(r) for r in [r"(?im)^\s*Domain\s+UUID:\s*(\S+)"] # virtinfo
]
manufacture_regexes = [
re.compile(r)
for r in [r"(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)"] # prtdiag
]
product_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)", # prtdiag
r"(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)", # prtconf
r"(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)", # prtconf
]
]
sn_regexes = [
re.compile(r)
for r in [
r"(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)", # prtdiag
r"(?i)Chassis\s+Serial#:\s*(\S+)", # virtinfo
r"(?i)chassis-sn:\s*(\S+)", # prtconf
]
]
obp_regexes = [
re.compile(r)
for r in [
r"(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)", # prtdiag
r"(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)", # prtconf
]
]
fw_regexes = [
re.compile(r)
for r in [r"(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)"] # prtdiag
]
uuid_regexes = [
re.compile(r) for r in [r"(?i)Domain\s+UUID:\s+(\S+)"] # virtinfo
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["serialnumber"] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[
0:2
] # Limit the number in case we found the data in multiple places
grains["biosversion"] = obp_rev.strip().replace("'", "")
grains["biosreleasedate"] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains["systemfirmware"] = fw_rev.strip().replace("'", "")
grains["systemfirmwaredate"] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["uuid"] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["manufacture"] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains["product"] = t_productname
grains["productname"] = t_productname
break
elif osdata["kernel"] == "AIX":
cmd = salt.utils.path.which("prtconf")
if cmd:
data = __salt__["cmd.run"]("{0}".format(cmd)) + os.linesep
for dest, regstring in (
("serialnumber", r"(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)"),
("systemfirmware", r"(?im)^\s*Firmware\s+Version:\s+(.*)"),
):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", "")
product_regexes = [re.compile(r"(?im)^\s*System\s+Model:\s+(\S+)")]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["manufacturer"], grains["productname"] = (
res.group(1).strip().replace("'", "").split(",")
)
break
else:
log.error("The 'prtconf' binary was not found in $PATH.")
return grains
def get_server_id():
# Provides:
# server_id
if salt.utils.platform.is_proxy():
return {}
id_ = __opts__.get("id", "")
hash_ = int(hashlib.sha256(id_.encode()).hexdigest(), 16)
return {"server_id": abs(hash_ % (2 ** 31))}
def get_master():
# Provides:
# master
return {"master": __opts__.get("master", "")}
def default_gateway():
grains = {}
ip_bin = salt.utils.path.which("ip")
if not ip_bin:
return {}
grains["ip_gw"] = False
grains["ip4_gw"] = False
grains["ip6_gw"] = False
for ip_version in ("4", "6"):
try:
out = __salt__["cmd.run"]([ip_bin, "-" + ip_version, "route", "show"])
for line in out.splitlines():
if line.startswith("default"):
grains["ip_gw"] = True
grains["ip{0}_gw".format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == "via":
grains["ip{0}_gw".format(ip_version)] = gw_ip
break
except Exception: # pylint: disable=broad-except
continue
return grains
def kernelparams():
try:
with salt.utils.files.fopen("/proc/cmdline", "r") as fhr:
cmdline = fhr.read()
grains = {"kernelparams": []}
for data in [
item.split("=") for item in salt.utils.args.shlex_split(cmdline)
]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains["kernelparams"] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug("Failed to read /proc/cmdline: %s", exc)
return grains
| true | true |
f72c39d04f46b4659fec28e1537a34671c4a461f | 439 | py | Python | people/templatetags/people_extras.py | hayatbayramolsa/website | 22a00a1de8b5902c559e4b48df27fa5c1329f16a | [
"WTFPL"
] | 1 | 2020-02-07T17:38:14.000Z | 2020-02-07T17:38:14.000Z | people/templatetags/people_extras.py | hayatbayramolsa/website | 22a00a1de8b5902c559e4b48df27fa5c1329f16a | [
"WTFPL"
] | null | null | null | people/templatetags/people_extras.py | hayatbayramolsa/website | 22a00a1de8b5902c559e4b48df27fa5c1329f16a | [
"WTFPL"
] | null | null | null | from django import template
register = template.Library()
def fontawesome(icon_name, size=""):
"""
Generate fontawesome syntax for HTML.
Usage:
{% fontawesome "iconname" %}
{% fontawesome "iconname" "size" %}
Size values are: lg, 2x, 3x, 4x, 5x
"""
if len(size) > 0:
size = "fa-%s" % size
return '<i class="fa fa-%s %s"></i>' % (icon_name, size)
register.simple_tag(fontawesome)
| 19.086957 | 60 | 0.587699 | from django import template
register = template.Library()
def fontawesome(icon_name, size=""):
if len(size) > 0:
size = "fa-%s" % size
return '<i class="fa fa-%s %s"></i>' % (icon_name, size)
register.simple_tag(fontawesome)
| true | true |
f72c3a32e58db3f2d9a4b04faa87382ae4209bcf | 314 | py | Python | symarray/symarray/calculus/tests/test_arrays.py | tonyfast/uarray | 72fe4a0b86b26208747c95c828c66b8284d435d4 | [
"BSD-3-Clause"
] | null | null | null | symarray/symarray/calculus/tests/test_arrays.py | tonyfast/uarray | 72fe4a0b86b26208747c95c828c66b8284d435d4 | [
"BSD-3-Clause"
] | null | null | null | symarray/symarray/calculus/tests/test_arrays.py | tonyfast/uarray | 72fe4a0b86b26208747c95c828c66b8284d435d4 | [
"BSD-3-Clause"
] | null | null | null |
from symarray.calculus.integers import Integer
from symarray.calculus.arrays import Array
from symarray.shape import NDShape
def test_basic():
a = Array('a')
b = Array('b', shape=NDShape((Integer('n1'), Integer('n2'))))
n = Integer('n')
expr = a+n*a+2+b
print(expr.shape)
print(expr[1])
| 22.428571 | 65 | 0.659236 |
from symarray.calculus.integers import Integer
from symarray.calculus.arrays import Array
from symarray.shape import NDShape
def test_basic():
a = Array('a')
b = Array('b', shape=NDShape((Integer('n1'), Integer('n2'))))
n = Integer('n')
expr = a+n*a+2+b
print(expr.shape)
print(expr[1])
| true | true |
f72c3ac1f20334925f3e4c702afd2d9868b7b904 | 3,221 | py | Python | u-tokyo/2018-summer/dataset.py | PandaDrunkard/proex | c303f051721d9f271d8187957a4458dc5f4558b1 | [
"MIT"
] | null | null | null | u-tokyo/2018-summer/dataset.py | PandaDrunkard/proex | c303f051721d9f271d8187957a4458dc5f4558b1 | [
"MIT"
] | null | null | null | u-tokyo/2018-summer/dataset.py | PandaDrunkard/proex | c303f051721d9f271d8187957a4458dc5f4558b1 | [
"MIT"
] | null | null | null | import math
def load_image(filename, append_index=False):
content = [line.strip().split(' ') for line in open(filename)][0]
r = list(map(int, content[0::3]))
g = list(map(int, content[1::3]))
b = list(map(int, content[2::3]))
if append_index:
return list(zip(r,g,b,range(len(r))))
else:
return list(zip(r,g,b,))
WHITE=tuple([255,255,255])
def format_image(raw):
formated = [[]]
for i, element in enumerate(raw):
if element[:3] == WHITE:
subset = raw[i::i+1]
is_white_line = (len(subset) > 2)
for sub in raw[i::i+1]:
if sub[:3] != WHITE:
is_white_line = False
break
if is_white_line:
formated.append([])
else:
formated[-1].append(element)
else:
formated[-1].append(element)
formated = formated[:-1]
return formated
def format_square(raw):
size = len(raw)
w = int(math.sqrt(size))
formatted = []
for i in range(len(raw) // w):
formatted.append([])
for j in range(w):
formatted[-1].append(raw[i*w + j])
return formatted
def width(raw):
size = len(raw)
for i in range(1, size//2):
rgb = raw[i][:3]
if rgb == WHITE:
subset = raw[i::i+1]
# print(f'{(i+1)}: {subset[:5]}')
is_white = map(lambda subelm: subelm[:3]==WHITE, subset)
if all(is_white):
return i+1
return -1
def format_image2(raw):
w = width(raw)
formatted = []
for i in range(len(raw) // w):
formatted.append([])
for j in range(w):
formatted[-1].append(raw[i*w + j])
return formatted
def test(append_index=False):
return load_image('./test.txt', append_index=append_index)
def image1(append_index=False):
return load_image('./image1.txt', append_index=append_index)
def image2(append_index=False):
return load_image('./image2.txt', append_index=append_index)
def image3(append_index=False):
return load_image('./image3.txt', append_index=append_index)
TIF_HEADER_ARRAY=[
77,77, 0,42, 0, 0, 0, 8, 0, 7, 1, 0, 0, 4, 0, 0,
0, 1, 0, 0, 0, 0, 1, 1, 0, 4, 0, 0, 0, 1, 0, 0,
0, 0, 1, 2, 0, 3, 0, 0, 0, 3, 0, 0, 0,98, 1, 6,
0, 3, 0, 0, 0, 1, 0, 2, 0, 0, 1,17, 0, 4, 0, 0,
0, 1, 0, 0, 0,104, 1,21, 0, 3, 0, 0, 0, 1, 0, 3,
0, 0, 1,23, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 8, 0, 8, 0, 8
]
def save_image(filename, image):
hight = len(image)
width = len(image[0])
b_hight = (hight).to_bytes(4, byteorder='big')
b_width = (width).to_bytes(4, byteorder='big')
b_s = (hight*width*3).to_bytes(4, byteorder='big')
# set hight/width/s
header = TIF_HEADER_ARRAY[:]
for i in range(4):
header[18 + i] = b_width[i]
header[30 + i] = b_hight[i]
header[90 + i] = b_s[i]
b_header = bytes(header)
content = []
for r in range(hight):
for c in range(width):
content += list(image[r][c][:3])
b_content = bytes(content)
with open(filename, 'wb') as out:
out.write(b_header)
out.write(b_content) | 30.386792 | 69 | 0.535548 | import math
def load_image(filename, append_index=False):
content = [line.strip().split(' ') for line in open(filename)][0]
r = list(map(int, content[0::3]))
g = list(map(int, content[1::3]))
b = list(map(int, content[2::3]))
if append_index:
return list(zip(r,g,b,range(len(r))))
else:
return list(zip(r,g,b,))
WHITE=tuple([255,255,255])
def format_image(raw):
formated = [[]]
for i, element in enumerate(raw):
if element[:3] == WHITE:
subset = raw[i::i+1]
is_white_line = (len(subset) > 2)
for sub in raw[i::i+1]:
if sub[:3] != WHITE:
is_white_line = False
break
if is_white_line:
formated.append([])
else:
formated[-1].append(element)
else:
formated[-1].append(element)
formated = formated[:-1]
return formated
def format_square(raw):
size = len(raw)
w = int(math.sqrt(size))
formatted = []
for i in range(len(raw) // w):
formatted.append([])
for j in range(w):
formatted[-1].append(raw[i*w + j])
return formatted
def width(raw):
size = len(raw)
for i in range(1, size//2):
rgb = raw[i][:3]
if rgb == WHITE:
subset = raw[i::i+1]
is_white = map(lambda subelm: subelm[:3]==WHITE, subset)
if all(is_white):
return i+1
return -1
def format_image2(raw):
w = width(raw)
formatted = []
for i in range(len(raw) // w):
formatted.append([])
for j in range(w):
formatted[-1].append(raw[i*w + j])
return formatted
def test(append_index=False):
return load_image('./test.txt', append_index=append_index)
def image1(append_index=False):
return load_image('./image1.txt', append_index=append_index)
def image2(append_index=False):
return load_image('./image2.txt', append_index=append_index)
def image3(append_index=False):
return load_image('./image3.txt', append_index=append_index)
TIF_HEADER_ARRAY=[
77,77, 0,42, 0, 0, 0, 8, 0, 7, 1, 0, 0, 4, 0, 0,
0, 1, 0, 0, 0, 0, 1, 1, 0, 4, 0, 0, 0, 1, 0, 0,
0, 0, 1, 2, 0, 3, 0, 0, 0, 3, 0, 0, 0,98, 1, 6,
0, 3, 0, 0, 0, 1, 0, 2, 0, 0, 1,17, 0, 4, 0, 0,
0, 1, 0, 0, 0,104, 1,21, 0, 3, 0, 0, 0, 1, 0, 3,
0, 0, 1,23, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 8, 0, 8, 0, 8
]
def save_image(filename, image):
hight = len(image)
width = len(image[0])
b_hight = (hight).to_bytes(4, byteorder='big')
b_width = (width).to_bytes(4, byteorder='big')
b_s = (hight*width*3).to_bytes(4, byteorder='big')
header = TIF_HEADER_ARRAY[:]
for i in range(4):
header[18 + i] = b_width[i]
header[30 + i] = b_hight[i]
header[90 + i] = b_s[i]
b_header = bytes(header)
content = []
for r in range(hight):
for c in range(width):
content += list(image[r][c][:3])
b_content = bytes(content)
with open(filename, 'wb') as out:
out.write(b_header)
out.write(b_content) | true | true |
f72c3b061208c98f8b6103c531da45e38011c75c | 92,091 | py | Python | pandas/util/testing.py | mimikaTU/pandas | 573d4e7e1b354e7ee0cb12280ec58835207106ea | [
"BSD-3-Clause"
] | 1 | 2020-01-18T09:57:03.000Z | 2020-01-18T09:57:03.000Z | pandas/util/testing.py | Kaya176/pandas | 4fb963b6a3261940de5891323a8d217087a2a9a1 | [
"BSD-3-Clause"
] | 1 | 2018-03-22T16:06:03.000Z | 2018-03-22T16:06:03.000Z | pandas/util/testing.py | Kaya176/pandas | 4fb963b6a3261940de5891323a8d217087a2a9a1 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import division
# pylint: disable-msg=W0402
import re
import string
import sys
import tempfile
import warnings
import inspect
import os
import subprocess
import locale
import traceback
from datetime import datetime
from functools import wraps
from contextlib import contextmanager
from numpy.random import randn, rand
import numpy as np
import pandas as pd
from pandas.core.arrays import ExtensionArray
from pandas.core.dtypes.missing import array_equivalent
from pandas.core.dtypes.common import (
is_datetimelike_v_numeric,
is_datetimelike_v_object,
is_number, is_bool,
needs_i8_conversion,
is_categorical_dtype,
is_interval_dtype,
is_sequence,
is_list_like)
from pandas.io.formats.printing import pprint_thing
from pandas.core.algorithms import take_1d
import pandas.core.common as com
import pandas.compat as compat
from pandas.compat import (
filter, map, zip, range, unichr, lrange, lmap, lzip, u, callable, Counter,
raise_with_traceback, httplib, StringIO, PY3)
from pandas import (bdate_range, CategoricalIndex, Categorical, IntervalIndex,
DatetimeIndex, TimedeltaIndex, PeriodIndex, RangeIndex,
Index, MultiIndex,
Series, DataFrame, Panel)
from pandas._libs import testing as _testing
from pandas.io.common import urlopen
N = 30
K = 4
_RAISE_NETWORK_ERROR_DEFAULT = False
# set testing_mode
_testing_mode_warnings = (DeprecationWarning, compat.ResourceWarning)
def set_testing_mode():
# set the testing mode filters
testing_mode = os.environ.get('PANDAS_TESTING_MODE', 'None')
if 'deprecate' in testing_mode:
warnings.simplefilter('always', _testing_mode_warnings)
def reset_testing_mode():
# reset the testing mode filters
testing_mode = os.environ.get('PANDAS_TESTING_MODE', 'None')
if 'deprecate' in testing_mode:
warnings.simplefilter('ignore', _testing_mode_warnings)
set_testing_mode()
def reset_display_options():
"""
Reset the display options for printing and representing objects.
"""
pd.reset_option('^display.', silent=True)
def round_trip_pickle(obj, path=None):
"""
Pickle an object and then read it again.
Parameters
----------
obj : pandas object
The object to pickle and then re-read.
path : str, default None
The path where the pickled object is written and then read.
Returns
-------
round_trip_pickled_object : pandas object
The original object that was pickled and then re-read.
"""
if path is None:
path = u('__{random_bytes}__.pickle'.format(random_bytes=rands(10)))
with ensure_clean(path) as path:
pd.to_pickle(obj, path)
return pd.read_pickle(path)
def round_trip_pathlib(writer, reader, path=None):
"""
Write an object to file specified by a pathlib.Path and read it back
Parameters
----------
writer : callable bound to pandas object
IO writing function (e.g. DataFrame.to_csv )
reader : callable
IO reading function (e.g. pd.read_csv )
path : str, default None
The path where the object is written and then read.
Returns
-------
round_trip_object : pandas object
The original object that was serialized and then re-read.
"""
import pytest
Path = pytest.importorskip('pathlib').Path
if path is None:
path = '___pathlib___'
with ensure_clean(path) as path:
writer(Path(path))
obj = reader(Path(path))
return obj
def round_trip_localpath(writer, reader, path=None):
"""
Write an object to file specified by a py.path LocalPath and read it back
Parameters
----------
writer : callable bound to pandas object
IO writing function (e.g. DataFrame.to_csv )
reader : callable
IO reading function (e.g. pd.read_csv )
path : str, default None
The path where the object is written and then read.
Returns
-------
round_trip_object : pandas object
The original object that was serialized and then re-read.
"""
import pytest
LocalPath = pytest.importorskip('py.path').local
if path is None:
path = '___localpath___'
with ensure_clean(path) as path:
writer(LocalPath(path))
obj = reader(LocalPath(path))
return obj
@contextmanager
def decompress_file(path, compression):
"""
Open a compressed file and return a file object
Parameters
----------
path : str
The path where the file is read from
compression : {'gzip', 'bz2', 'zip', 'xz', None}
Name of the decompression to use
Returns
-------
f : file object
"""
if compression is None:
f = open(path, 'rb')
elif compression == 'gzip':
import gzip
f = gzip.open(path, 'rb')
elif compression == 'bz2':
import bz2
f = bz2.BZ2File(path, 'rb')
elif compression == 'xz':
lzma = compat.import_lzma()
f = lzma.LZMAFile(path, 'rb')
elif compression == 'zip':
import zipfile
zip_file = zipfile.ZipFile(path)
zip_names = zip_file.namelist()
if len(zip_names) == 1:
f = zip_file.open(zip_names.pop())
else:
raise ValueError('ZIP file {} error. Only one file per ZIP.'
.format(path))
else:
msg = 'Unrecognized compression type: {}'.format(compression)
raise ValueError(msg)
yield f
f.close()
def assert_almost_equal(left, right, check_exact=False,
check_dtype='equiv', check_less_precise=False,
**kwargs):
"""
Check that the left and right objects are approximately equal.
Parameters
----------
left : object
right : object
check_exact : bool, default False
Whether to compare number exactly.
check_dtype: bool, default True
check dtype if both a and b are the same type
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
If int, then specify the digits to compare
"""
if isinstance(left, pd.Index):
return assert_index_equal(left, right, check_exact=check_exact,
exact=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
elif isinstance(left, pd.Series):
return assert_series_equal(left, right, check_exact=check_exact,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
elif isinstance(left, pd.DataFrame):
return assert_frame_equal(left, right, check_exact=check_exact,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
else:
# other sequences
if check_dtype:
if is_number(left) and is_number(right):
# do not compare numeric classes, like np.float64 and float
pass
elif is_bool(left) and is_bool(right):
# do not compare bool classes, like np.bool_ and bool
pass
else:
if (isinstance(left, np.ndarray) or
isinstance(right, np.ndarray)):
obj = 'numpy array'
else:
obj = 'Input'
assert_class_equal(left, right, obj=obj)
return _testing.assert_almost_equal(
left, right,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
def _check_isinstance(left, right, cls):
"""
Helper method for our assert_* methods that ensures that
the two objects being compared have the right type before
proceeding with the comparison.
Parameters
----------
left : The first object being compared.
right : The second object being compared.
cls : The class type to check against.
Raises
------
AssertionError : Either `left` or `right` is not an instance of `cls`.
"""
err_msg = "{name} Expected type {exp_type}, found {act_type} instead"
cls_name = cls.__name__
if not isinstance(left, cls):
raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
act_type=type(left)))
if not isinstance(right, cls):
raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
act_type=type(right)))
def assert_dict_equal(left, right, compare_keys=True):
_check_isinstance(left, right, dict)
return _testing.assert_dict_equal(left, right, compare_keys=compare_keys)
def randbool(size=(), p=0.5):
return rand(*size) <= p
RANDS_CHARS = np.array(list(string.ascii_letters + string.digits),
dtype=(np.str_, 1))
RANDU_CHARS = np.array(list(u("").join(map(unichr, lrange(1488, 1488 + 26))) +
string.digits), dtype=(np.unicode_, 1))
def rands_array(nchars, size, dtype='O'):
"""Generate an array of byte strings."""
retval = (np.random.choice(RANDS_CHARS, size=nchars * np.prod(size))
.view((np.str_, nchars)).reshape(size))
if dtype is None:
return retval
else:
return retval.astype(dtype)
def randu_array(nchars, size, dtype='O'):
"""Generate an array of unicode strings."""
retval = (np.random.choice(RANDU_CHARS, size=nchars * np.prod(size))
.view((np.unicode_, nchars)).reshape(size))
if dtype is None:
return retval
else:
return retval.astype(dtype)
def rands(nchars):
"""
Generate one random byte string.
See `rands_array` if you want to create an array of random strings.
"""
return ''.join(np.random.choice(RANDS_CHARS, nchars))
def randu(nchars):
"""
Generate one random unicode string.
See `randu_array` if you want to create an array of random unicode strings.
"""
return ''.join(np.random.choice(RANDU_CHARS, nchars))
def close(fignum=None):
from matplotlib.pyplot import get_fignums, close as _close
if fignum is None:
for fignum in get_fignums():
_close(fignum)
else:
_close(fignum)
# -----------------------------------------------------------------------------
# locale utilities
def check_output(*popenargs, **kwargs):
# shamelessly taken from Python 2.7 source
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, stderr=subprocess.PIPE,
*popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd, output=output)
return output
def _default_locale_getter():
try:
raw_locales = check_output(['locale -a'], shell=True)
except subprocess.CalledProcessError as e:
raise type(e)("{exception}, the 'locale -a' command cannot be found "
"on your system".format(exception=e))
return raw_locales
def get_locales(prefix=None, normalize=True,
locale_getter=_default_locale_getter):
"""Get all the locales that are available on the system.
Parameters
----------
prefix : str
If not ``None`` then return only those locales with the prefix
provided. For example to get all English language locales (those that
start with ``"en"``), pass ``prefix="en"``.
normalize : bool
Call ``locale.normalize`` on the resulting list of available locales.
If ``True``, only locales that can be set without throwing an
``Exception`` are returned.
locale_getter : callable
The function to use to retrieve the current locales. This should return
a string with each locale separated by a newline character.
Returns
-------
locales : list of strings
A list of locale strings that can be set with ``locale.setlocale()``.
For example::
locale.setlocale(locale.LC_ALL, locale_string)
On error will return None (no locale available, e.g. Windows)
"""
try:
raw_locales = locale_getter()
except Exception:
return None
try:
# raw_locales is "\n" separated list of locales
# it may contain non-decodable parts, so split
# extract what we can and then rejoin.
raw_locales = raw_locales.split(b'\n')
out_locales = []
for x in raw_locales:
if PY3:
out_locales.append(str(
x, encoding=pd.options.display.encoding))
else:
out_locales.append(str(x))
except TypeError:
pass
if prefix is None:
return _valid_locales(out_locales, normalize)
found = re.compile('{prefix}.*'.format(prefix=prefix)) \
.findall('\n'.join(out_locales))
return _valid_locales(found, normalize)
@contextmanager
def set_locale(new_locale, lc_var=locale.LC_ALL):
"""Context manager for temporarily setting a locale.
Parameters
----------
new_locale : str or tuple
A string of the form <language_country>.<encoding>. For example to set
the current locale to US English with a UTF8 encoding, you would pass
"en_US.UTF-8".
Notes
-----
This is useful when you want to run a particular block of code under a
particular locale, without globally setting the locale. This probably isn't
thread-safe.
"""
current_locale = locale.getlocale()
try:
locale.setlocale(lc_var, new_locale)
try:
normalized_locale = locale.getlocale()
except ValueError:
yield new_locale
else:
if com._all_not_none(*normalized_locale):
yield '.'.join(normalized_locale)
else:
yield new_locale
finally:
locale.setlocale(lc_var, current_locale)
def _can_set_locale(lc):
"""Check to see if we can set a locale without throwing an exception.
Parameters
----------
lc : str
The locale to attempt to set.
Returns
-------
isvalid : bool
Whether the passed locale can be set
"""
try:
with set_locale(lc):
pass
except locale.Error: # horrible name for a Exception subclass
return False
else:
return True
def _valid_locales(locales, normalize):
"""Return a list of normalized locales that do not throw an ``Exception``
when set.
Parameters
----------
locales : str
A string where each locale is separated by a newline.
normalize : bool
Whether to call ``locale.normalize`` on each locale.
Returns
-------
valid_locales : list
A list of valid locales.
"""
if normalize:
normalizer = lambda x: locale.normalize(x.strip())
else:
normalizer = lambda x: x.strip()
return list(filter(_can_set_locale, map(normalizer, locales)))
# -----------------------------------------------------------------------------
# Stdout / stderr decorators
def capture_stdout(f):
"""
Decorator to capture stdout in a buffer so that it can be checked
(or suppressed) during testing.
Parameters
----------
f : callable
The test that is capturing stdout.
Returns
-------
f : callable
The decorated test ``f``, which captures stdout.
Examples
--------
>>> from pandas.util.testing import capture_stdout
>>>
>>> import sys
>>>
>>> @capture_stdout
... def test_print_pass():
... print("foo")
... out = sys.stdout.getvalue()
... assert out == "foo\n"
>>>
>>> @capture_stdout
... def test_print_fail():
... print("foo")
... out = sys.stdout.getvalue()
... assert out == "bar\n"
...
AssertionError: assert 'foo\n' == 'bar\n'
"""
@wraps(f)
def wrapper(*args, **kwargs):
try:
sys.stdout = StringIO()
f(*args, **kwargs)
finally:
sys.stdout = sys.__stdout__
return wrapper
def capture_stderr(f):
"""
Decorator to capture stderr in a buffer so that it can be checked
(or suppressed) during testing.
Parameters
----------
f : callable
The test that is capturing stderr.
Returns
-------
f : callable
The decorated test ``f``, which captures stderr.
Examples
--------
>>> from pandas.util.testing import capture_stderr
>>>
>>> import sys
>>>
>>> @capture_stderr
... def test_stderr_pass():
... sys.stderr.write("foo")
... out = sys.stderr.getvalue()
... assert out == "foo\n"
>>>
>>> @capture_stderr
... def test_stderr_fail():
... sys.stderr.write("foo")
... out = sys.stderr.getvalue()
... assert out == "bar\n"
...
AssertionError: assert 'foo\n' == 'bar\n'
"""
@wraps(f)
def wrapper(*args, **kwargs):
try:
sys.stderr = StringIO()
f(*args, **kwargs)
finally:
sys.stderr = sys.__stderr__
return wrapper
# -----------------------------------------------------------------------------
# Console debugging tools
def debug(f, *args, **kwargs):
from pdb import Pdb as OldPdb
try:
from IPython.core.debugger import Pdb
kw = dict(color_scheme='Linux')
except ImportError:
Pdb = OldPdb
kw = {}
pdb = Pdb(**kw)
return pdb.runcall(f, *args, **kwargs)
def pudebug(f, *args, **kwargs):
import pudb
return pudb.runcall(f, *args, **kwargs)
def set_trace():
from IPython.core.debugger import Pdb
try:
Pdb(color_scheme='Linux').set_trace(sys._getframe().f_back)
except Exception:
from pdb import Pdb as OldPdb
OldPdb().set_trace(sys._getframe().f_back)
# -----------------------------------------------------------------------------
# contextmanager to ensure the file cleanup
@contextmanager
def ensure_clean(filename=None, return_filelike=False):
"""Gets a temporary path and agrees to remove on close.
Parameters
----------
filename : str (optional)
if None, creates a temporary file which is then removed when out of
scope. if passed, creates temporary file with filename as ending.
return_filelike : bool (default False)
if True, returns a file-like which is *always* cleaned. Necessary for
savefig and other functions which want to append extensions.
"""
filename = filename or ''
fd = None
if return_filelike:
f = tempfile.TemporaryFile(suffix=filename)
try:
yield f
finally:
f.close()
else:
# don't generate tempfile if using a path with directory specified
if len(os.path.dirname(filename)):
raise ValueError("Can't pass a qualified name to ensure_clean()")
try:
fd, filename = tempfile.mkstemp(suffix=filename)
except UnicodeEncodeError:
import pytest
pytest.skip('no unicode file names on this system')
try:
yield filename
finally:
try:
os.close(fd)
except Exception as e:
print("Couldn't close file descriptor: {fdesc} (file: {fname})"
.format(fdesc=fd, fname=filename))
try:
if os.path.exists(filename):
os.remove(filename)
except Exception as e:
print("Exception on removing file: {error}".format(error=e))
def get_data_path(f=''):
"""Return the path of a data file, these are relative to the current test
directory.
"""
# get our callers file
_, filename, _, _, _, _ = inspect.getouterframes(inspect.currentframe())[1]
base_dir = os.path.abspath(os.path.dirname(filename))
return os.path.join(base_dir, 'data', f)
# -----------------------------------------------------------------------------
# Comparators
def equalContents(arr1, arr2):
"""Checks if the set of unique elements of arr1 and arr2 are equivalent.
"""
return frozenset(arr1) == frozenset(arr2)
def assert_index_equal(left, right, exact='equiv', check_names=True,
check_less_precise=False, check_exact=True,
check_categorical=True, obj='Index'):
"""Check that left and right Index are equal.
Parameters
----------
left : Index
right : Index
exact : bool / string {'equiv'}, default False
Whether to check the Index class, dtype and inferred_type
are identical. If 'equiv', then RangeIndex can be substituted for
Int64Index as well.
check_names : bool, default True
Whether to check the names attribute.
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
If int, then specify the digits to compare
check_exact : bool, default True
Whether to compare number exactly.
check_categorical : bool, default True
Whether to compare internal Categorical exactly.
obj : str, default 'Index'
Specify object name being compared, internally used to show appropriate
assertion message
"""
def _check_types(l, r, obj='Index'):
if exact:
assert_class_equal(left, right, exact=exact, obj=obj)
assert_attr_equal('dtype', l, r, obj=obj)
# allow string-like to have different inferred_types
if l.inferred_type in ('string', 'unicode'):
assert r.inferred_type in ('string', 'unicode')
else:
assert_attr_equal('inferred_type', l, r, obj=obj)
def _get_ilevel_values(index, level):
# accept level number only
unique = index.levels[level]
labels = index.labels[level]
filled = take_1d(unique.values, labels, fill_value=unique._na_value)
values = unique._shallow_copy(filled, name=index.names[level])
return values
# instance validation
_check_isinstance(left, right, Index)
# class / dtype comparison
_check_types(left, right, obj=obj)
# level comparison
if left.nlevels != right.nlevels:
msg1 = '{obj} levels are different'.format(obj=obj)
msg2 = '{nlevels}, {left}'.format(nlevels=left.nlevels, left=left)
msg3 = '{nlevels}, {right}'.format(nlevels=right.nlevels, right=right)
raise_assert_detail(obj, msg1, msg2, msg3)
# length comparison
if len(left) != len(right):
msg1 = '{obj} length are different'.format(obj=obj)
msg2 = '{length}, {left}'.format(length=len(left), left=left)
msg3 = '{length}, {right}'.format(length=len(right), right=right)
raise_assert_detail(obj, msg1, msg2, msg3)
# MultiIndex special comparison for little-friendly error messages
if left.nlevels > 1:
for level in range(left.nlevels):
# cannot use get_level_values here because it can change dtype
llevel = _get_ilevel_values(left, level)
rlevel = _get_ilevel_values(right, level)
lobj = 'MultiIndex level [{level}]'.format(level=level)
assert_index_equal(llevel, rlevel,
exact=exact, check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact, obj=lobj)
# get_level_values may change dtype
_check_types(left.levels[level], right.levels[level], obj=obj)
if check_exact:
if not left.equals(right):
diff = np.sum((left.values != right.values)
.astype(int)) * 100.0 / len(left)
msg = '{obj} values are different ({pct} %)'.format(
obj=obj, pct=np.round(diff, 5))
raise_assert_detail(obj, msg, left, right)
else:
_testing.assert_almost_equal(left.values, right.values,
check_less_precise=check_less_precise,
check_dtype=exact,
obj=obj, lobj=left, robj=right)
# metadata comparison
if check_names:
assert_attr_equal('names', left, right, obj=obj)
if isinstance(left, pd.PeriodIndex) or isinstance(right, pd.PeriodIndex):
assert_attr_equal('freq', left, right, obj=obj)
if (isinstance(left, pd.IntervalIndex) or
isinstance(right, pd.IntervalIndex)):
assert_attr_equal('closed', left, right, obj=obj)
if check_categorical:
if is_categorical_dtype(left) or is_categorical_dtype(right):
assert_categorical_equal(left.values, right.values,
obj='{obj} category'.format(obj=obj))
def assert_class_equal(left, right, exact=True, obj='Input'):
"""checks classes are equal."""
def repr_class(x):
if isinstance(x, Index):
# return Index as it is to include values in the error message
return x
try:
return x.__class__.__name__
except AttributeError:
return repr(type(x))
if exact == 'equiv':
if type(left) != type(right):
# allow equivalence of Int64Index/RangeIndex
types = set([type(left).__name__, type(right).__name__])
if len(types - set(['Int64Index', 'RangeIndex'])):
msg = '{obj} classes are not equivalent'.format(obj=obj)
raise_assert_detail(obj, msg, repr_class(left),
repr_class(right))
elif exact:
if type(left) != type(right):
msg = '{obj} classes are different'.format(obj=obj)
raise_assert_detail(obj, msg, repr_class(left),
repr_class(right))
def assert_attr_equal(attr, left, right, obj='Attributes'):
"""checks attributes are equal. Both objects must have attribute.
Parameters
----------
attr : str
Attribute name being compared.
left : object
right : object
obj : str, default 'Attributes'
Specify object name being compared, internally used to show appropriate
assertion message
"""
left_attr = getattr(left, attr)
right_attr = getattr(right, attr)
if left_attr is right_attr:
return True
elif (is_number(left_attr) and np.isnan(left_attr) and
is_number(right_attr) and np.isnan(right_attr)):
# np.nan
return True
try:
result = left_attr == right_attr
except TypeError:
# datetimetz on rhs may raise TypeError
result = False
if not isinstance(result, bool):
result = result.all()
if result:
return True
else:
msg = 'Attribute "{attr}" are different'.format(attr=attr)
raise_assert_detail(obj, msg, left_attr, right_attr)
def assert_is_valid_plot_return_object(objs):
import matplotlib.pyplot as plt
if isinstance(objs, (pd.Series, np.ndarray)):
for el in objs.ravel():
msg = ('one of \'objs\' is not a matplotlib Axes instance, type '
'encountered {name!r}').format(name=el.__class__.__name__)
assert isinstance(el, (plt.Axes, dict)), msg
else:
assert isinstance(objs, (plt.Artist, tuple, dict)), \
('objs is neither an ndarray of Artist instances nor a '
'single Artist instance, tuple, or dict, "objs" is a {name!r}'
).format(name=objs.__class__.__name__)
def isiterable(obj):
return hasattr(obj, '__iter__')
def is_sorted(seq):
if isinstance(seq, (Index, Series)):
seq = seq.values
# sorting does not change precisions
return assert_numpy_array_equal(seq, np.sort(np.array(seq)))
def assert_categorical_equal(left, right, check_dtype=True,
obj='Categorical', check_category_order=True):
"""Test that Categoricals are equivalent.
Parameters
----------
left, right : Categorical
Categoricals to compare
check_dtype : bool, default True
Check that integer dtype of the codes are the same
obj : str, default 'Categorical'
Specify object name being compared, internally used to show appropriate
assertion message
check_category_order : bool, default True
Whether the order of the categories should be compared, which
implies identical integer codes. If False, only the resulting
values are compared. The ordered attribute is
checked regardless.
"""
_check_isinstance(left, right, Categorical)
if check_category_order:
assert_index_equal(left.categories, right.categories,
obj='{obj}.categories'.format(obj=obj))
assert_numpy_array_equal(left.codes, right.codes,
check_dtype=check_dtype,
obj='{obj}.codes'.format(obj=obj))
else:
assert_index_equal(left.categories.sort_values(),
right.categories.sort_values(),
obj='{obj}.categories'.format(obj=obj))
assert_index_equal(left.categories.take(left.codes),
right.categories.take(right.codes),
obj='{obj}.values'.format(obj=obj))
assert_attr_equal('ordered', left, right, obj=obj)
def raise_assert_detail(obj, message, left, right, diff=None):
if isinstance(left, np.ndarray):
left = pprint_thing(left)
elif is_categorical_dtype(left):
left = repr(left)
if isinstance(right, np.ndarray):
right = pprint_thing(right)
elif is_categorical_dtype(right):
right = repr(right)
msg = """{obj} are different
{message}
[left]: {left}
[right]: {right}""".format(obj=obj, message=message, left=left, right=right)
if diff is not None:
msg += "\n[diff]: {diff}".format(diff=diff)
raise AssertionError(msg)
def assert_numpy_array_equal(left, right, strict_nan=False,
check_dtype=True, err_msg=None,
obj='numpy array', check_same=None):
""" Checks that 'np.ndarray' is equivalent
Parameters
----------
left : np.ndarray or iterable
right : np.ndarray or iterable
strict_nan : bool, default False
If True, consider NaN and None to be different.
check_dtype: bool, default True
check dtype if both a and b are np.ndarray
err_msg : str, default None
If provided, used as assertion message
obj : str, default 'numpy array'
Specify object name being compared, internally used to show appropriate
assertion message
check_same : None|'copy'|'same', default None
Ensure left and right refer/do not refer to the same memory area
"""
# instance validation
# Show a detailed error message when classes are different
assert_class_equal(left, right, obj=obj)
# both classes must be an np.ndarray
_check_isinstance(left, right, np.ndarray)
def _get_base(obj):
return obj.base if getattr(obj, 'base', None) is not None else obj
left_base = _get_base(left)
right_base = _get_base(right)
if check_same == 'same':
if left_base is not right_base:
msg = "{left!r} is not {right!r}".format(
left=left_base, right=right_base)
raise AssertionError(msg)
elif check_same == 'copy':
if left_base is right_base:
msg = "{left!r} is {right!r}".format(
left=left_base, right=right_base)
raise AssertionError(msg)
def _raise(left, right, err_msg):
if err_msg is None:
if left.shape != right.shape:
raise_assert_detail(obj, '{obj} shapes are different'
.format(obj=obj), left.shape, right.shape)
diff = 0
for l, r in zip(left, right):
# count up differences
if not array_equivalent(l, r, strict_nan=strict_nan):
diff += 1
diff = diff * 100.0 / left.size
msg = '{obj} values are different ({pct} %)'.format(
obj=obj, pct=np.round(diff, 5))
raise_assert_detail(obj, msg, left, right)
raise AssertionError(err_msg)
# compare shape and values
if not array_equivalent(left, right, strict_nan=strict_nan):
_raise(left, right, err_msg)
if check_dtype:
if isinstance(left, np.ndarray) and isinstance(right, np.ndarray):
assert_attr_equal('dtype', left, right, obj=obj)
return True
def assert_extension_array_equal(left, right):
"""Check that left and right ExtensionArrays are equal.
Parameters
----------
left, right : ExtensionArray
The two arrays to compare
Notes
-----
Missing values are checked separately from valid values.
A mask of missing values is computed for each and checked to match.
The remaining all-valid values are cast to object dtype and checked.
"""
assert isinstance(left, ExtensionArray)
assert left.dtype == right.dtype
left_na = left.isna()
right_na = right.isna()
assert_numpy_array_equal(left_na, right_na)
left_valid = left[~left_na].astype(object)
right_valid = right[~right_na].astype(object)
assert_numpy_array_equal(left_valid, right_valid)
# This could be refactored to use the NDFrame.equals method
def assert_series_equal(left, right, check_dtype=True,
check_index_type='equiv',
check_series_type=True,
check_less_precise=False,
check_names=True,
check_exact=False,
check_datetimelike_compat=False,
check_categorical=True,
obj='Series'):
"""Check that left and right Series are equal.
Parameters
----------
left : Series
right : Series
check_dtype : bool, default True
Whether to check the Series dtype is identical.
check_index_type : bool / string {'equiv'}, default 'equiv'
Whether to check the Index class, dtype and inferred_type
are identical.
check_series_type : bool, default True
Whether to check the Series class is identical.
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
If int, then specify the digits to compare
check_exact : bool, default False
Whether to compare number exactly.
check_names : bool, default True
Whether to check the Series and Index names attribute.
check_datetimelike_compat : bool, default False
Compare datetime-like which is comparable ignoring dtype.
check_categorical : bool, default True
Whether to compare internal Categorical exactly.
obj : str, default 'Series'
Specify object name being compared, internally used to show appropriate
assertion message
"""
# instance validation
_check_isinstance(left, right, Series)
if check_series_type:
# ToDo: There are some tests using rhs is sparse
# lhs is dense. Should use assert_class_equal in future
assert isinstance(left, type(right))
# assert_class_equal(left, right, obj=obj)
# length comparison
if len(left) != len(right):
msg1 = '{len}, {left}'.format(len=len(left), left=left.index)
msg2 = '{len}, {right}'.format(len=len(right), right=right.index)
raise_assert_detail(obj, 'Series length are different', msg1, msg2)
# index comparison
assert_index_equal(left.index, right.index, exact=check_index_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.index'.format(obj=obj))
if check_dtype:
# We want to skip exact dtype checking when `check_categorical`
# is False. We'll still raise if only one is a `Categorical`,
# regardless of `check_categorical`
if (is_categorical_dtype(left) and is_categorical_dtype(right) and
not check_categorical):
pass
else:
assert_attr_equal('dtype', left, right)
if check_exact:
assert_numpy_array_equal(left.get_values(), right.get_values(),
check_dtype=check_dtype,
obj='{obj}'.format(obj=obj),)
elif check_datetimelike_compat:
# we want to check only if we have compat dtypes
# e.g. integer and M|m are NOT compat, but we can simply check
# the values in that case
if (is_datetimelike_v_numeric(left, right) or
is_datetimelike_v_object(left, right) or
needs_i8_conversion(left) or
needs_i8_conversion(right)):
# datetimelike may have different objects (e.g. datetime.datetime
# vs Timestamp) but will compare equal
if not Index(left.values).equals(Index(right.values)):
msg = ('[datetimelike_compat=True] {left} is not equal to '
'{right}.').format(left=left.values, right=right.values)
raise AssertionError(msg)
else:
assert_numpy_array_equal(left.get_values(), right.get_values(),
check_dtype=check_dtype)
elif is_interval_dtype(left) or is_interval_dtype(right):
# TODO: big hack here
left = pd.IntervalIndex(left)
right = pd.IntervalIndex(right)
assert_index_equal(left, right, obj='{obj}.index'.format(obj=obj))
else:
_testing.assert_almost_equal(left.get_values(), right.get_values(),
check_less_precise=check_less_precise,
check_dtype=check_dtype,
obj='{obj}'.format(obj=obj))
# metadata comparison
if check_names:
assert_attr_equal('name', left, right, obj=obj)
if check_categorical:
if is_categorical_dtype(left) or is_categorical_dtype(right):
assert_categorical_equal(left.values, right.values,
obj='{obj} category'.format(obj=obj))
# This could be refactored to use the NDFrame.equals method
def assert_frame_equal(left, right, check_dtype=True,
check_index_type='equiv',
check_column_type='equiv',
check_frame_type=True,
check_less_precise=False,
check_names=True,
by_blocks=False,
check_exact=False,
check_datetimelike_compat=False,
check_categorical=True,
check_like=False,
obj='DataFrame'):
"""Check that left and right DataFrame are equal.
Parameters
----------
left : DataFrame
right : DataFrame
check_dtype : bool, default True
Whether to check the DataFrame dtype is identical.
check_index_type : bool / string {'equiv'}, default False
Whether to check the Index class, dtype and inferred_type
are identical.
check_column_type : bool / string {'equiv'}, default False
Whether to check the columns class, dtype and inferred_type
are identical.
check_frame_type : bool, default False
Whether to check the DataFrame class is identical.
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
If int, then specify the digits to compare
check_names : bool, default True
Whether to check the Index names attribute.
by_blocks : bool, default False
Specify how to compare internal data. If False, compare by columns.
If True, compare by blocks.
check_exact : bool, default False
Whether to compare number exactly.
check_datetimelike_compat : bool, default False
Compare datetime-like which is comparable ignoring dtype.
check_categorical : bool, default True
Whether to compare internal Categorical exactly.
check_like : bool, default False
If true, ignore the order of rows & columns
obj : str, default 'DataFrame'
Specify object name being compared, internally used to show appropriate
assertion message
"""
# instance validation
_check_isinstance(left, right, DataFrame)
if check_frame_type:
# ToDo: There are some tests using rhs is SparseDataFrame
# lhs is DataFrame. Should use assert_class_equal in future
assert isinstance(left, type(right))
# assert_class_equal(left, right, obj=obj)
# shape comparison
if left.shape != right.shape:
raise_assert_detail(obj,
'DataFrame shape mismatch',
'{shape!r}'.format(shape=left.shape),
'{shape!r}'.format(shape=right.shape))
if check_like:
left, right = left.reindex_like(right), right
# index comparison
assert_index_equal(left.index, right.index, exact=check_index_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.index'.format(obj=obj))
# column comparison
assert_index_equal(left.columns, right.columns, exact=check_column_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.columns'.format(obj=obj))
# compare by blocks
if by_blocks:
rblocks = right._to_dict_of_blocks()
lblocks = left._to_dict_of_blocks()
for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
assert dtype in lblocks
assert dtype in rblocks
assert_frame_equal(lblocks[dtype], rblocks[dtype],
check_dtype=check_dtype, obj='DataFrame.blocks')
# compare by columns
else:
for i, col in enumerate(left.columns):
assert col in right
lcol = left.iloc[:, i]
rcol = right.iloc[:, i]
assert_series_equal(
lcol, rcol, check_dtype=check_dtype,
check_index_type=check_index_type,
check_less_precise=check_less_precise,
check_exact=check_exact, check_names=check_names,
check_datetimelike_compat=check_datetimelike_compat,
check_categorical=check_categorical,
obj='DataFrame.iloc[:, {idx}]'.format(idx=i))
def assert_panel_equal(left, right,
check_dtype=True,
check_panel_type=False,
check_less_precise=False,
check_names=False,
by_blocks=False,
obj='Panel'):
"""Check that left and right Panels are equal.
Parameters
----------
left : Panel (or nd)
right : Panel (or nd)
check_dtype : bool, default True
Whether to check the Panel dtype is identical.
check_panel_type : bool, default False
Whether to check the Panel class is identical.
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
If int, then specify the digits to compare
check_names : bool, default True
Whether to check the Index names attribute.
by_blocks : bool, default False
Specify how to compare internal data. If False, compare by columns.
If True, compare by blocks.
obj : str, default 'Panel'
Specify the object name being compared, internally used to show
the appropriate assertion message.
"""
if check_panel_type:
assert_class_equal(left, right, obj=obj)
for axis in left._AXIS_ORDERS:
left_ind = getattr(left, axis)
right_ind = getattr(right, axis)
assert_index_equal(left_ind, right_ind, check_names=check_names)
if by_blocks:
rblocks = right._to_dict_of_blocks()
lblocks = left._to_dict_of_blocks()
for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
assert dtype in lblocks
assert dtype in rblocks
array_equivalent(lblocks[dtype].values, rblocks[dtype].values)
else:
# can potentially be slow
for i, item in enumerate(left._get_axis(0)):
msg = "non-matching item (right) '{item}'".format(item=item)
assert item in right, msg
litem = left.iloc[i]
ritem = right.iloc[i]
assert_frame_equal(litem, ritem,
check_less_precise=check_less_precise,
check_names=check_names)
for i, item in enumerate(right._get_axis(0)):
msg = "non-matching item (left) '{item}'".format(item=item)
assert item in left, msg
# -----------------------------------------------------------------------------
# Sparse
def assert_sp_array_equal(left, right, check_dtype=True):
"""Check that the left and right SparseArray are equal.
Parameters
----------
left : SparseArray
right : SparseArray
check_dtype : bool, default True
Whether to check the data dtype is identical.
"""
_check_isinstance(left, right, pd.SparseArray)
assert_numpy_array_equal(left.sp_values, right.sp_values,
check_dtype=check_dtype)
# SparseIndex comparison
assert isinstance(left.sp_index, pd._libs.sparse.SparseIndex)
assert isinstance(right.sp_index, pd._libs.sparse.SparseIndex)
if not left.sp_index.equals(right.sp_index):
raise_assert_detail('SparseArray.index', 'index are not equal',
left.sp_index, right.sp_index)
assert_attr_equal('fill_value', left, right)
if check_dtype:
assert_attr_equal('dtype', left, right)
assert_numpy_array_equal(left.values, right.values,
check_dtype=check_dtype)
def assert_sp_series_equal(left, right, check_dtype=True, exact_indices=True,
check_series_type=True, check_names=True,
obj='SparseSeries'):
"""Check that the left and right SparseSeries are equal.
Parameters
----------
left : SparseSeries
right : SparseSeries
check_dtype : bool, default True
Whether to check the Series dtype is identical.
exact_indices : bool, default True
check_series_type : bool, default True
Whether to check the SparseSeries class is identical.
check_names : bool, default True
Whether to check the SparseSeries name attribute.
obj : str, default 'SparseSeries'
Specify the object name being compared, internally used to show
the appropriate assertion message.
"""
_check_isinstance(left, right, pd.SparseSeries)
if check_series_type:
assert_class_equal(left, right, obj=obj)
assert_index_equal(left.index, right.index,
obj='{obj}.index'.format(obj=obj))
assert_sp_array_equal(left.block.values, right.block.values)
if check_names:
assert_attr_equal('name', left, right)
if check_dtype:
assert_attr_equal('dtype', left, right)
assert_numpy_array_equal(left.values, right.values)
def assert_sp_frame_equal(left, right, check_dtype=True, exact_indices=True,
check_frame_type=True, obj='SparseDataFrame'):
"""Check that the left and right SparseDataFrame are equal.
Parameters
----------
left : SparseDataFrame
right : SparseDataFrame
check_dtype : bool, default True
Whether to check the Series dtype is identical.
exact_indices : bool, default True
SparseSeries SparseIndex objects must be exactly the same,
otherwise just compare dense representations.
check_frame_type : bool, default True
Whether to check the SparseDataFrame class is identical.
obj : str, default 'SparseDataFrame'
Specify the object name being compared, internally used to show
the appropriate assertion message.
"""
_check_isinstance(left, right, pd.SparseDataFrame)
if check_frame_type:
assert_class_equal(left, right, obj=obj)
assert_index_equal(left.index, right.index,
obj='{obj}.index'.format(obj=obj))
assert_index_equal(left.columns, right.columns,
obj='{obj}.columns'.format(obj=obj))
for col, series in compat.iteritems(left):
assert (col in right)
# trade-off?
if exact_indices:
assert_sp_series_equal(series, right[col],
check_dtype=check_dtype)
else:
assert_series_equal(series.to_dense(), right[col].to_dense(),
check_dtype=check_dtype)
assert_attr_equal('default_fill_value', left, right, obj=obj)
# do I care?
# assert(left.default_kind == right.default_kind)
for col in right:
assert (col in left)
# -----------------------------------------------------------------------------
# Others
def assert_contains_all(iterable, dic):
for k in iterable:
assert k in dic, "Did not contain item: '{key!r}'".format(key=k)
def assert_copy(iter1, iter2, **eql_kwargs):
"""
iter1, iter2: iterables that produce elements
comparable with assert_almost_equal
Checks that the elements are equal, but not
the same object. (Does not check that items
in sequences are also not the same object)
"""
for elem1, elem2 in zip(iter1, iter2):
assert_almost_equal(elem1, elem2, **eql_kwargs)
msg = ("Expected object {obj1!r} and object {obj2!r} to be "
"different objects, but they were the same object."
).format(obj1=type(elem1), obj2=type(elem2))
assert elem1 is not elem2, msg
def getCols(k):
return string.ascii_uppercase[:k]
def getArangeMat():
return np.arange(N * K).reshape((N, K))
# make index
def makeStringIndex(k=10, name=None):
return Index(rands_array(nchars=10, size=k), name=name)
def makeUnicodeIndex(k=10, name=None):
return Index(randu_array(nchars=10, size=k), name=name)
def makeCategoricalIndex(k=10, n=3, name=None, **kwargs):
""" make a length k index or n categories """
x = rands_array(nchars=4, size=n)
return CategoricalIndex(np.random.choice(x, k), name=name, **kwargs)
def makeIntervalIndex(k=10, name=None, **kwargs):
""" make a length k IntervalIndex """
x = np.linspace(0, 100, num=(k + 1))
return IntervalIndex.from_breaks(x, name=name, **kwargs)
def makeBoolIndex(k=10, name=None):
if k == 1:
return Index([True], name=name)
elif k == 2:
return Index([False, True], name=name)
return Index([False, True] + [False] * (k - 2), name=name)
def makeIntIndex(k=10, name=None):
return Index(lrange(k), name=name)
def makeUIntIndex(k=10, name=None):
return Index([2**63 + i for i in lrange(k)], name=name)
def makeRangeIndex(k=10, name=None, **kwargs):
return RangeIndex(0, k, 1, name=name, **kwargs)
def makeFloatIndex(k=10, name=None):
values = sorted(np.random.random_sample(k)) - np.random.random_sample(1)
return Index(values * (10 ** np.random.randint(0, 9)), name=name)
def makeDateIndex(k=10, freq='B', name=None, **kwargs):
dt = datetime(2000, 1, 1)
dr = bdate_range(dt, periods=k, freq=freq, name=name)
return DatetimeIndex(dr, name=name, **kwargs)
def makeTimedeltaIndex(k=10, freq='D', name=None, **kwargs):
return TimedeltaIndex(start='1 day', periods=k, freq=freq,
name=name, **kwargs)
def makePeriodIndex(k=10, name=None, **kwargs):
dt = datetime(2000, 1, 1)
dr = PeriodIndex(start=dt, periods=k, freq='B', name=name, **kwargs)
return dr
def makeMultiIndex(k=10, names=None, **kwargs):
return MultiIndex.from_product(
(('foo', 'bar'), (1, 2)), names=names, **kwargs)
def all_index_generator(k=10):
"""Generator which can be iterated over to get instances of all the various
index classes.
Parameters
----------
k: length of each of the index instances
"""
all_make_index_funcs = [makeIntIndex, makeFloatIndex, makeStringIndex,
makeUnicodeIndex, makeDateIndex, makePeriodIndex,
makeTimedeltaIndex, makeBoolIndex, makeRangeIndex,
makeIntervalIndex,
makeCategoricalIndex]
for make_index_func in all_make_index_funcs:
yield make_index_func(k=k)
def index_subclass_makers_generator():
make_index_funcs = [
makeDateIndex, makePeriodIndex,
makeTimedeltaIndex, makeRangeIndex,
makeIntervalIndex, makeCategoricalIndex,
makeMultiIndex
]
for make_index_func in make_index_funcs:
yield make_index_func
def all_timeseries_index_generator(k=10):
"""Generator which can be iterated over to get instances of all the classes
which represent time-seires.
Parameters
----------
k: length of each of the index instances
"""
make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex]
for make_index_func in make_index_funcs:
yield make_index_func(k=k)
# make series
def makeFloatSeries(name=None):
index = makeStringIndex(N)
return Series(randn(N), index=index, name=name)
def makeStringSeries(name=None):
index = makeStringIndex(N)
return Series(randn(N), index=index, name=name)
def makeObjectSeries(name=None):
dateIndex = makeDateIndex(N)
dateIndex = Index(dateIndex, dtype=object)
index = makeStringIndex(N)
return Series(dateIndex, index=index, name=name)
def getSeriesData():
index = makeStringIndex(N)
return {c: Series(randn(N), index=index) for c in getCols(K)}
def makeTimeSeries(nper=None, freq='B', name=None):
if nper is None:
nper = N
return Series(randn(nper), index=makeDateIndex(nper, freq=freq), name=name)
def makePeriodSeries(nper=None, name=None):
if nper is None:
nper = N
return Series(randn(nper), index=makePeriodIndex(nper), name=name)
def getTimeSeriesData(nper=None, freq='B'):
return {c: makeTimeSeries(nper, freq) for c in getCols(K)}
def getPeriodData(nper=None):
return {c: makePeriodSeries(nper) for c in getCols(K)}
# make frame
def makeTimeDataFrame(nper=None, freq='B'):
data = getTimeSeriesData(nper, freq)
return DataFrame(data)
def makeDataFrame():
data = getSeriesData()
return DataFrame(data)
def getMixedTypeDict():
index = Index(['a', 'b', 'c', 'd', 'e'])
data = {
'A': [0., 1., 2., 3., 4.],
'B': [0., 1., 0., 1., 0.],
'C': ['foo1', 'foo2', 'foo3', 'foo4', 'foo5'],
'D': bdate_range('1/1/2009', periods=5)
}
return index, data
def makeMixedDataFrame():
return DataFrame(getMixedTypeDict()[1])
def makePeriodFrame(nper=None):
data = getPeriodData(nper)
return DataFrame(data)
def makePanel(nper=None):
with warnings.catch_warnings(record=True):
cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]]
data = {c: makeTimeDataFrame(nper) for c in cols}
return Panel.fromDict(data)
def makePeriodPanel(nper=None):
with warnings.catch_warnings(record=True):
cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]]
data = {c: makePeriodFrame(nper) for c in cols}
return Panel.fromDict(data)
def makeCustomIndex(nentries, nlevels, prefix='#', names=False, ndupe_l=None,
idx_type=None):
"""Create an index/multindex with given dimensions, levels, names, etc'
nentries - number of entries in index
nlevels - number of levels (> 1 produces multindex)
prefix - a string prefix for labels
names - (Optional), bool or list of strings. if True will use default
names, if false will use no names, if a list is given, the name of
each level in the index will be taken from the list.
ndupe_l - (Optional), list of ints, the number of rows for which the
label will repeated at the corresponding level, you can specify just
the first few, the rest will use the default ndupe_l of 1.
len(ndupe_l) <= nlevels.
idx_type - "i"/"f"/"s"/"u"/"dt"/"p"/"td".
If idx_type is not None, `idx_nlevels` must be 1.
"i"/"f" creates an integer/float index,
"s"/"u" creates a string/unicode index
"dt" create a datetime index.
"td" create a datetime index.
if unspecified, string labels will be generated.
"""
if ndupe_l is None:
ndupe_l = [1] * nlevels
assert (is_sequence(ndupe_l) and len(ndupe_l) <= nlevels)
assert (names is None or names is False or
names is True or len(names) is nlevels)
assert idx_type is None or \
(idx_type in ('i', 'f', 's', 'u', 'dt', 'p', 'td') and nlevels == 1)
if names is True:
# build default names
names = [prefix + str(i) for i in range(nlevels)]
if names is False:
# pass None to index constructor for no name
names = None
# make singelton case uniform
if isinstance(names, compat.string_types) and nlevels == 1:
names = [names]
# specific 1D index type requested?
idx_func = dict(i=makeIntIndex, f=makeFloatIndex,
s=makeStringIndex, u=makeUnicodeIndex,
dt=makeDateIndex, td=makeTimedeltaIndex,
p=makePeriodIndex).get(idx_type)
if idx_func:
idx = idx_func(nentries)
# but we need to fill in the name
if names:
idx.name = names[0]
return idx
elif idx_type is not None:
raise ValueError('"{idx_type}" is not a legal value for `idx_type`, '
'use "i"/"f"/"s"/"u"/"dt/"p"/"td".'
.format(idx_type=idx_type))
if len(ndupe_l) < nlevels:
ndupe_l.extend([1] * (nlevels - len(ndupe_l)))
assert len(ndupe_l) == nlevels
assert all(x > 0 for x in ndupe_l)
tuples = []
for i in range(nlevels):
def keyfunc(x):
import re
numeric_tuple = re.sub(r"[^\d_]_?", "", x).split("_")
return lmap(int, numeric_tuple)
# build a list of lists to create the index from
div_factor = nentries // ndupe_l[i] + 1
cnt = Counter()
for j in range(div_factor):
label = '{prefix}_l{i}_g{j}'.format(prefix=prefix, i=i, j=j)
cnt[label] = ndupe_l[i]
# cute Counter trick
result = list(sorted(cnt.elements(), key=keyfunc))[:nentries]
tuples.append(result)
tuples = lzip(*tuples)
# convert tuples to index
if nentries == 1:
# we have a single level of tuples, i.e. a regular Index
index = Index(tuples[0], name=names[0])
elif nlevels == 1:
name = None if names is None else names[0]
index = Index((x[0] for x in tuples), name=name)
else:
index = MultiIndex.from_tuples(tuples, names=names)
return index
def makeCustomDataframe(nrows, ncols, c_idx_names=True, r_idx_names=True,
c_idx_nlevels=1, r_idx_nlevels=1, data_gen_f=None,
c_ndupe_l=None, r_ndupe_l=None, dtype=None,
c_idx_type=None, r_idx_type=None):
"""
nrows, ncols - number of data rows/cols
c_idx_names, idx_names - False/True/list of strings, yields No names ,
default names or uses the provided names for the levels of the
corresponding index. You can provide a single string when
c_idx_nlevels ==1.
c_idx_nlevels - number of levels in columns index. > 1 will yield MultiIndex
r_idx_nlevels - number of levels in rows index. > 1 will yield MultiIndex
data_gen_f - a function f(row,col) which return the data value
at that position, the default generator used yields values of the form
"RxCy" based on position.
c_ndupe_l, r_ndupe_l - list of integers, determines the number
of duplicates for each label at a given level of the corresponding
index. The default `None` value produces a multiplicity of 1 across
all levels, i.e. a unique index. Will accept a partial list of length
N < idx_nlevels, for just the first N levels. If ndupe doesn't divide
nrows/ncol, the last label might have lower multiplicity.
dtype - passed to the DataFrame constructor as is, in case you wish to
have more control in conjuncion with a custom `data_gen_f`
r_idx_type, c_idx_type - "i"/"f"/"s"/"u"/"dt"/"td".
If idx_type is not None, `idx_nlevels` must be 1.
"i"/"f" creates an integer/float index,
"s"/"u" creates a string/unicode index
"dt" create a datetime index.
"td" create a timedelta index.
if unspecified, string labels will be generated.
Examples:
# 5 row, 3 columns, default names on both, single index on both axis
>> makeCustomDataframe(5,3)
# make the data a random int between 1 and 100
>> mkdf(5,3,data_gen_f=lambda r,c:randint(1,100))
# 2-level multiindex on rows with each label duplicated
# twice on first level, default names on both axis, single
# index on both axis
>> a=makeCustomDataframe(5,3,r_idx_nlevels=2,r_ndupe_l=[2])
# DatetimeIndex on row, index with unicode labels on columns
# no names on either axis
>> a=makeCustomDataframe(5,3,c_idx_names=False,r_idx_names=False,
r_idx_type="dt",c_idx_type="u")
# 4-level multindex on rows with names provided, 2-level multindex
# on columns with default labels and default names.
>> a=makeCustomDataframe(5,3,r_idx_nlevels=4,
r_idx_names=["FEE","FI","FO","FAM"],
c_idx_nlevels=2)
>> a=mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4)
"""
assert c_idx_nlevels > 0
assert r_idx_nlevels > 0
assert r_idx_type is None or \
(r_idx_type in ('i', 'f', 's',
'u', 'dt', 'p', 'td') and r_idx_nlevels == 1)
assert c_idx_type is None or \
(c_idx_type in ('i', 'f', 's',
'u', 'dt', 'p', 'td') and c_idx_nlevels == 1)
columns = makeCustomIndex(ncols, nlevels=c_idx_nlevels, prefix='C',
names=c_idx_names, ndupe_l=c_ndupe_l,
idx_type=c_idx_type)
index = makeCustomIndex(nrows, nlevels=r_idx_nlevels, prefix='R',
names=r_idx_names, ndupe_l=r_ndupe_l,
idx_type=r_idx_type)
# by default, generate data based on location
if data_gen_f is None:
data_gen_f = lambda r, c: "R{rows}C{cols}".format(rows=r, cols=c)
data = [[data_gen_f(r, c) for c in range(ncols)] for r in range(nrows)]
return DataFrame(data, index, columns, dtype=dtype)
def _create_missing_idx(nrows, ncols, density, random_state=None):
if random_state is None:
random_state = np.random
else:
random_state = np.random.RandomState(random_state)
# below is cribbed from scipy.sparse
size = int(np.round((1 - density) * nrows * ncols))
# generate a few more to ensure unique values
min_rows = 5
fac = 1.02
extra_size = min(size + min_rows, fac * size)
def _gen_unique_rand(rng, _extra_size):
ind = rng.rand(int(_extra_size))
return np.unique(np.floor(ind * nrows * ncols))[:size]
ind = _gen_unique_rand(random_state, extra_size)
while ind.size < size:
extra_size *= 1.05
ind = _gen_unique_rand(random_state, extra_size)
j = np.floor(ind * 1. / nrows).astype(int)
i = (ind - j * nrows).astype(int)
return i.tolist(), j.tolist()
def makeMissingCustomDataframe(nrows, ncols, density=.9, random_state=None,
c_idx_names=True, r_idx_names=True,
c_idx_nlevels=1, r_idx_nlevels=1,
data_gen_f=None,
c_ndupe_l=None, r_ndupe_l=None, dtype=None,
c_idx_type=None, r_idx_type=None):
"""
Parameters
----------
Density : float, optional
Float in (0, 1) that gives the percentage of non-missing numbers in
the DataFrame.
random_state : {np.random.RandomState, int}, optional
Random number generator or random seed.
See makeCustomDataframe for descriptions of the rest of the parameters.
"""
df = makeCustomDataframe(nrows, ncols, c_idx_names=c_idx_names,
r_idx_names=r_idx_names,
c_idx_nlevels=c_idx_nlevels,
r_idx_nlevels=r_idx_nlevels,
data_gen_f=data_gen_f,
c_ndupe_l=c_ndupe_l, r_ndupe_l=r_ndupe_l,
dtype=dtype, c_idx_type=c_idx_type,
r_idx_type=r_idx_type)
i, j = _create_missing_idx(nrows, ncols, density, random_state)
df.values[i, j] = np.nan
return df
def makeMissingDataframe(density=.9, random_state=None):
df = makeDataFrame()
i, j = _create_missing_idx(*df.shape, density=density,
random_state=random_state)
df.values[i, j] = np.nan
return df
def add_nans(panel):
I, J, N = panel.shape
for i, item in enumerate(panel.items):
dm = panel[item]
for j, col in enumerate(dm.columns):
dm[col][:i + j] = np.NaN
return panel
def add_nans_panel4d(panel4d):
for l, label in enumerate(panel4d.labels):
panel = panel4d[label]
add_nans(panel)
return panel4d
class TestSubDict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
def optional_args(decorator):
"""allows a decorator to take optional positional and keyword arguments.
Assumes that taking a single, callable, positional argument means that
it is decorating a function, i.e. something like this::
@my_decorator
def function(): pass
Calls decorator with decorator(f, *args, **kwargs)"""
@wraps(decorator)
def wrapper(*args, **kwargs):
def dec(f):
return decorator(f, *args, **kwargs)
is_decorating = not kwargs and len(args) == 1 and callable(args[0])
if is_decorating:
f = args[0]
args = []
return dec(f)
else:
return dec
return wrapper
# skip tests on exceptions with this message
_network_error_messages = (
# 'urlopen error timed out',
# 'timeout: timed out',
# 'socket.timeout: timed out',
'timed out',
'Server Hangup',
'HTTP Error 503: Service Unavailable',
'502: Proxy Error',
'HTTP Error 502: internal error',
'HTTP Error 502',
'HTTP Error 503',
'HTTP Error 403',
'HTTP Error 400',
'Temporary failure in name resolution',
'Name or service not known',
'Connection refused',
'certificate verify',
)
# or this e.errno/e.reason.errno
_network_errno_vals = (
101, # Network is unreachable
111, # Connection refused
110, # Connection timed out
104, # Connection reset Error
54, # Connection reset by peer
60, # urllib.error.URLError: [Errno 60] Connection timed out
)
# Both of the above shouldn't mask real issues such as 404's
# or refused connections (changed DNS).
# But some tests (test_data yahoo) contact incredibly flakey
# servers.
# and conditionally raise on these exception types
_network_error_classes = (IOError, httplib.HTTPException)
if sys.version_info >= (3, 3):
_network_error_classes += (TimeoutError,) # noqa
def can_connect(url, error_classes=_network_error_classes):
"""Try to connect to the given url. True if succeeds, False if IOError
raised
Parameters
----------
url : basestring
The URL to try to connect to
Returns
-------
connectable : bool
Return True if no IOError (unable to connect) or URLError (bad url) was
raised
"""
try:
with urlopen(url):
pass
except error_classes:
return False
else:
return True
@optional_args
def network(t, url="http://www.google.com",
raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT,
check_before_test=False,
error_classes=_network_error_classes,
skip_errnos=_network_errno_vals,
_skip_on_messages=_network_error_messages,
):
"""
Label a test as requiring network connection and, if an error is
encountered, only raise if it does not find a network connection.
In comparison to ``network``, this assumes an added contract to your test:
you must assert that, under normal conditions, your test will ONLY fail if
it does not have network connectivity.
You can call this in 3 ways: as a standard decorator, with keyword
arguments, or with a positional argument that is the url to check.
Parameters
----------
t : callable
The test requiring network connectivity.
url : path
The url to test via ``pandas.io.common.urlopen`` to check
for connectivity. Defaults to 'http://www.google.com'.
raise_on_error : bool
If True, never catches errors.
check_before_test : bool
If True, checks connectivity before running the test case.
error_classes : tuple or Exception
error classes to ignore. If not in ``error_classes``, raises the error.
defaults to IOError. Be careful about changing the error classes here.
skip_errnos : iterable of int
Any exception that has .errno or .reason.erno set to one
of these values will be skipped with an appropriate
message.
_skip_on_messages: iterable of string
any exception e for which one of the strings is
a substring of str(e) will be skipped with an appropriate
message. Intended to suppress errors where an errno isn't available.
Notes
-----
* ``raise_on_error`` supercedes ``check_before_test``
Returns
-------
t : callable
The decorated test ``t``, with checks for connectivity errors.
Example
-------
Tests decorated with @network will fail if it's possible to make a network
connection to another URL (defaults to google.com)::
>>> from pandas.util.testing import network
>>> from pandas.io.common import urlopen
>>> @network
... def test_network():
... with urlopen("rabbit://bonanza.com"):
... pass
Traceback
...
URLError: <urlopen error unknown url type: rabit>
You can specify alternative URLs::
>>> @network("http://www.yahoo.com")
... def test_something_with_yahoo():
... raise IOError("Failure Message")
>>> test_something_with_yahoo()
Traceback (most recent call last):
...
IOError: Failure Message
If you set check_before_test, it will check the url first and not run the
test on failure::
>>> @network("failing://url.blaher", check_before_test=True)
... def test_something():
... print("I ran!")
... raise ValueError("Failure")
>>> test_something()
Traceback (most recent call last):
...
Errors not related to networking will always be raised.
"""
from pytest import skip
t.network = True
@compat.wraps(t)
def wrapper(*args, **kwargs):
if check_before_test and not raise_on_error:
if not can_connect(url, error_classes):
skip()
try:
return t(*args, **kwargs)
except Exception as e:
errno = getattr(e, 'errno', None)
if not errno and hasattr(errno, "reason"):
errno = getattr(e.reason, 'errno', None)
if errno in skip_errnos:
skip("Skipping test due to known errno"
" and error {error}".format(error=e))
try:
e_str = traceback.format_exc(e)
except Exception:
e_str = str(e)
if any(m.lower() in e_str.lower() for m in _skip_on_messages):
skip("Skipping test because exception "
"message is known and error {error}".format(error=e))
if not isinstance(e, error_classes):
raise
if raise_on_error or can_connect(url, error_classes):
raise
else:
skip("Skipping test due to lack of connectivity"
" and error {error}".format(e))
return wrapper
with_connectivity_check = network
class SimpleMock(object):
"""
Poor man's mocking object
Note: only works for new-style classes, assumes __getattribute__ exists.
>>> a = type("Duck",(),{})
>>> a.attr1,a.attr2 ="fizz","buzz"
>>> b = SimpleMock(a,"attr1","bar")
>>> b.attr1 == "bar" and b.attr2 == "buzz"
True
>>> a.attr1 == "fizz" and a.attr2 == "buzz"
True
"""
def __init__(self, obj, *args, **kwds):
assert(len(args) % 2 == 0)
attrs = kwds.get("attrs", {})
for k, v in zip(args[::2], args[1::2]):
# dict comprehensions break 2.6
attrs[k] = v
self.attrs = attrs
self.obj = obj
def __getattribute__(self, name):
attrs = object.__getattribute__(self, "attrs")
obj = object.__getattribute__(self, "obj")
return attrs.get(name, type(obj).__getattribute__(obj, name))
@contextmanager
def stdin_encoding(encoding=None):
"""
Context manager for running bits of code while emulating an arbitrary
stdin encoding.
>>> import sys
>>> _encoding = sys.stdin.encoding
>>> with stdin_encoding('AES'): sys.stdin.encoding
'AES'
>>> sys.stdin.encoding==_encoding
True
"""
import sys
_stdin = sys.stdin
sys.stdin = SimpleMock(sys.stdin, "encoding", encoding)
yield
sys.stdin = _stdin
def assert_raises_regex(_exception, _regexp, _callable=None,
*args, **kwargs):
r"""
Check that the specified Exception is raised and that the error message
matches a given regular expression pattern. This may be a regular
expression object or a string containing a regular expression suitable
for use by `re.search()`. This is a port of the `assertRaisesRegexp`
function from unittest in Python 2.7.
Examples
--------
>>> assert_raises_regex(ValueError, 'invalid literal for.*XYZ', int, 'XYZ')
>>> import re
>>> assert_raises_regex(ValueError, re.compile('literal'), int, 'XYZ')
If an exception of a different type is raised, it bubbles up.
>>> assert_raises_regex(TypeError, 'literal', int, 'XYZ')
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'XYZ'
>>> dct = dict()
>>> assert_raises_regex(KeyError, 'pear', dct.__getitem__, 'apple')
Traceback (most recent call last):
...
AssertionError: "pear" does not match "'apple'"
You can also use this in a with statement.
>>> with assert_raises_regex(TypeError, 'unsupported operand type\(s\)'):
... 1 + {}
>>> with assert_raises_regex(TypeError, 'banana'):
... 'apple'[0] = 'b'
Traceback (most recent call last):
...
AssertionError: "banana" does not match "'str' object does not support \
item assignment"
"""
manager = _AssertRaisesContextmanager(exception=_exception, regexp=_regexp)
if _callable is not None:
with manager:
_callable(*args, **kwargs)
else:
return manager
class _AssertRaisesContextmanager(object):
"""
Context manager behind `assert_raises_regex`.
"""
def __init__(self, exception, regexp=None):
"""
Initialize an _AssertRaisesContextManager instance.
Parameters
----------
exception : class
The expected Exception class.
regexp : str, default None
The regex to compare against the Exception message.
"""
self.exception = exception
if regexp is not None and not hasattr(regexp, "search"):
regexp = re.compile(regexp, re.DOTALL)
self.regexp = regexp
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, trace_back):
expected = self.exception
if not exc_type:
exp_name = getattr(expected, "__name__", str(expected))
raise AssertionError("{name} not raised.".format(name=exp_name))
return self.exception_matches(exc_type, exc_value, trace_back)
def exception_matches(self, exc_type, exc_value, trace_back):
"""
Check that the Exception raised matches the expected Exception
and expected error message regular expression.
Parameters
----------
exc_type : class
The type of Exception raised.
exc_value : Exception
The instance of `exc_type` raised.
trace_back : stack trace object
The traceback object associated with `exc_value`.
Returns
-------
is_matched : bool
Whether or not the Exception raised matches the expected
Exception class and expected error message regular expression.
Raises
------
AssertionError : The error message provided does not match
the expected error message regular expression.
"""
if issubclass(exc_type, self.exception):
if self.regexp is not None:
val = str(exc_value)
if not self.regexp.search(val):
msg = '"{pat}" does not match "{val}"'.format(
pat=self.regexp.pattern, val=val)
e = AssertionError(msg)
raise_with_traceback(e, trace_back)
return True
else:
# Failed, so allow Exception to bubble up.
return False
@contextmanager
def assert_produces_warning(expected_warning=Warning, filter_level="always",
clear=None, check_stacklevel=True):
"""
Context manager for running code expected to either raise a specific
warning, or not raise any warnings. Verifies that the code raises the
expected warning, and that it does not raise any other unexpected
warnings. It is basically a wrapper around ``warnings.catch_warnings``.
Parameters
----------
expected_warning : {Warning, False, None}, default Warning
The type of Exception raised. ``exception.Warning`` is the base
class for all warnings. To check that no warning is returned,
specify ``False`` or ``None``.
filter_level : str, default "always"
Specifies whether warnings are ignored, displayed, or turned
into errors.
Valid values are:
* "error" - turns matching warnings into exceptions
* "ignore" - discard the warning
* "always" - always emit a warning
* "default" - print the warning the first time it is generated
from each location
* "module" - print the warning the first time it is generated
from each module
* "once" - print the warning the first time it is generated
clear : str, default None
If not ``None`` then remove any previously raised warnings from
the ``__warningsregistry__`` to ensure that no warning messages are
suppressed by this context manager. If ``None`` is specified,
the ``__warningsregistry__`` keeps track of which warnings have been
shown, and does not show them again.
check_stacklevel : bool, default True
If True, displays the line that called the function containing
the warning to show were the function is called. Otherwise, the
line that implements the function is displayed.
Examples
--------
>>> import warnings
>>> with assert_produces_warning():
... warnings.warn(UserWarning())
...
>>> with assert_produces_warning(False):
... warnings.warn(RuntimeWarning())
...
Traceback (most recent call last):
...
AssertionError: Caused unexpected warning(s): ['RuntimeWarning'].
>>> with assert_produces_warning(UserWarning):
... warnings.warn(RuntimeWarning())
Traceback (most recent call last):
...
AssertionError: Did not see expected warning of class 'UserWarning'.
..warn:: This is *not* thread-safe.
"""
with warnings.catch_warnings(record=True) as w:
if clear is not None:
# make sure that we are clearning these warnings
# if they have happened before
# to guarantee that we will catch them
if not is_list_like(clear):
clear = [clear]
for m in clear:
try:
m.__warningregistry__.clear()
except Exception:
pass
saw_warning = False
warnings.simplefilter(filter_level)
yield w
extra_warnings = []
for actual_warning in w:
if (expected_warning and issubclass(actual_warning.category,
expected_warning)):
saw_warning = True
if check_stacklevel and issubclass(actual_warning.category,
(FutureWarning,
DeprecationWarning)):
from inspect import getframeinfo, stack
caller = getframeinfo(stack()[2][0])
msg = ("Warning not set with correct stacklevel. "
"File where warning is raised: {actual} != "
"{caller}. Warning message: {message}"
).format(actual=actual_warning.filename,
caller=caller.filename,
message=actual_warning.message)
assert actual_warning.filename == caller.filename, msg
else:
extra_warnings.append(actual_warning.category.__name__)
if expected_warning:
msg = "Did not see expected warning of class {name!r}.".format(
name=expected_warning.__name__)
assert saw_warning, msg
assert not extra_warnings, ("Caused unexpected warning(s): {extra!r}."
).format(extra=extra_warnings)
class RNGContext(object):
"""
Context manager to set the numpy random number generator speed. Returns
to the original value upon exiting the context manager.
Parameters
----------
seed : int
Seed for numpy.random.seed
Examples
--------
with RNGContext(42):
np.random.randn()
"""
def __init__(self, seed):
self.seed = seed
def __enter__(self):
self.start_state = np.random.get_state()
np.random.seed(self.seed)
def __exit__(self, exc_type, exc_value, traceback):
np.random.set_state(self.start_state)
@contextmanager
def use_numexpr(use, min_elements=None):
from pandas.core.computation import expressions as expr
if min_elements is None:
min_elements = expr._MIN_ELEMENTS
olduse = expr._USE_NUMEXPR
oldmin = expr._MIN_ELEMENTS
expr.set_use_numexpr(use)
expr._MIN_ELEMENTS = min_elements
yield
expr._MIN_ELEMENTS = oldmin
expr.set_use_numexpr(olduse)
def test_parallel(num_threads=2, kwargs_list=None):
"""Decorator to run the same function multiple times in parallel.
Parameters
----------
num_threads : int, optional
The number of times the function is run in parallel.
kwargs_list : list of dicts, optional
The list of kwargs to update original
function kwargs on different threads.
Notes
-----
This decorator does not pass the return value of the decorated function.
Original from scikit-image:
https://github.com/scikit-image/scikit-image/pull/1519
"""
assert num_threads > 0
has_kwargs_list = kwargs_list is not None
if has_kwargs_list:
assert len(kwargs_list) == num_threads
import threading
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
if has_kwargs_list:
update_kwargs = lambda i: dict(kwargs, **kwargs_list[i])
else:
update_kwargs = lambda i: kwargs
threads = []
for i in range(num_threads):
updated_kwargs = update_kwargs(i)
thread = threading.Thread(target=func, args=args,
kwargs=updated_kwargs)
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return inner
return wrapper
class SubclassedSeries(Series):
_metadata = ['testattr', 'name']
@property
def _constructor(self):
return SubclassedSeries
@property
def _constructor_expanddim(self):
return SubclassedDataFrame
class SubclassedDataFrame(DataFrame):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedDataFrame
@property
def _constructor_sliced(self):
return SubclassedSeries
class SubclassedSparseSeries(pd.SparseSeries):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedSparseSeries
@property
def _constructor_expanddim(self):
return SubclassedSparseDataFrame
class SubclassedSparseDataFrame(pd.SparseDataFrame):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedSparseDataFrame
@property
def _constructor_sliced(self):
return SubclassedSparseSeries
class SubclassedCategorical(Categorical):
@property
def _constructor(self):
return SubclassedCategorical
@contextmanager
def patch(ob, attr, value):
"""Temporarily patch an attribute of an object.
Parameters
----------
ob : any
The object to patch. This must support attribute assignment for `attr`.
attr : str
The name of the attribute to patch.
value : any
The temporary attribute to assign.
Examples
--------
>>> class C(object):
... attribute = 'original'
...
>>> C.attribute
'original'
>>> with patch(C, 'attribute', 'patched'):
... in_context = C.attribute
...
>>> in_context
'patched'
>>> C.attribute # the value is reset when the context manager exists
'original'
Correctly replaces attribute when the manager exits with an exception.
>>> with patch(C, 'attribute', 'patched'):
... in_context = C.attribute
... raise ValueError()
Traceback (most recent call last):
...
ValueError
>>> in_context
'patched'
>>> C.attribute
'original'
"""
noattr = object() # mark that the attribute never existed
old = getattr(ob, attr, noattr)
setattr(ob, attr, value)
try:
yield
finally:
if old is noattr:
delattr(ob, attr)
else:
setattr(ob, attr, old)
@contextmanager
def set_timezone(tz):
"""Context manager for temporarily setting a timezone.
Parameters
----------
tz : str
A string representing a valid timezone.
Examples
--------
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> tzlocal().tzname(datetime.now())
'IST'
>>> with set_timezone('US/Eastern'):
... tzlocal().tzname(datetime.now())
...
'EDT'
"""
import os
import time
def setTZ(tz):
if tz is None:
try:
del os.environ['TZ']
except KeyError:
pass
else:
os.environ['TZ'] = tz
time.tzset()
orig_tz = os.environ.get('TZ')
setTZ(tz)
try:
yield
finally:
setTZ(orig_tz)
def _make_skipna_wrapper(alternative, skipna_alternative=None):
"""Create a function for calling on an array.
Parameters
----------
alternative : function
The function to be called on the array with no NaNs.
Only used when 'skipna_alternative' is None.
skipna_alternative : function
The function to be called on the original array
Returns
-------
skipna_wrapper : function
"""
if skipna_alternative:
def skipna_wrapper(x):
return skipna_alternative(x.values)
else:
def skipna_wrapper(x):
nona = x.dropna()
if len(nona) == 0:
return np.nan
return alternative(nona)
return skipna_wrapper
| 32.854442 | 79 | 0.611059 | from __future__ import division
import re
import string
import sys
import tempfile
import warnings
import inspect
import os
import subprocess
import locale
import traceback
from datetime import datetime
from functools import wraps
from contextlib import contextmanager
from numpy.random import randn, rand
import numpy as np
import pandas as pd
from pandas.core.arrays import ExtensionArray
from pandas.core.dtypes.missing import array_equivalent
from pandas.core.dtypes.common import (
is_datetimelike_v_numeric,
is_datetimelike_v_object,
is_number, is_bool,
needs_i8_conversion,
is_categorical_dtype,
is_interval_dtype,
is_sequence,
is_list_like)
from pandas.io.formats.printing import pprint_thing
from pandas.core.algorithms import take_1d
import pandas.core.common as com
import pandas.compat as compat
from pandas.compat import (
filter, map, zip, range, unichr, lrange, lmap, lzip, u, callable, Counter,
raise_with_traceback, httplib, StringIO, PY3)
from pandas import (bdate_range, CategoricalIndex, Categorical, IntervalIndex,
DatetimeIndex, TimedeltaIndex, PeriodIndex, RangeIndex,
Index, MultiIndex,
Series, DataFrame, Panel)
from pandas._libs import testing as _testing
from pandas.io.common import urlopen
N = 30
K = 4
_RAISE_NETWORK_ERROR_DEFAULT = False
_testing_mode_warnings = (DeprecationWarning, compat.ResourceWarning)
def set_testing_mode():
testing_mode = os.environ.get('PANDAS_TESTING_MODE', 'None')
if 'deprecate' in testing_mode:
warnings.simplefilter('always', _testing_mode_warnings)
def reset_testing_mode():
testing_mode = os.environ.get('PANDAS_TESTING_MODE', 'None')
if 'deprecate' in testing_mode:
warnings.simplefilter('ignore', _testing_mode_warnings)
set_testing_mode()
def reset_display_options():
pd.reset_option('^display.', silent=True)
def round_trip_pickle(obj, path=None):
if path is None:
path = u('__{random_bytes}__.pickle'.format(random_bytes=rands(10)))
with ensure_clean(path) as path:
pd.to_pickle(obj, path)
return pd.read_pickle(path)
def round_trip_pathlib(writer, reader, path=None):
import pytest
Path = pytest.importorskip('pathlib').Path
if path is None:
path = '___pathlib___'
with ensure_clean(path) as path:
writer(Path(path))
obj = reader(Path(path))
return obj
def round_trip_localpath(writer, reader, path=None):
import pytest
LocalPath = pytest.importorskip('py.path').local
if path is None:
path = '___localpath___'
with ensure_clean(path) as path:
writer(LocalPath(path))
obj = reader(LocalPath(path))
return obj
@contextmanager
def decompress_file(path, compression):
if compression is None:
f = open(path, 'rb')
elif compression == 'gzip':
import gzip
f = gzip.open(path, 'rb')
elif compression == 'bz2':
import bz2
f = bz2.BZ2File(path, 'rb')
elif compression == 'xz':
lzma = compat.import_lzma()
f = lzma.LZMAFile(path, 'rb')
elif compression == 'zip':
import zipfile
zip_file = zipfile.ZipFile(path)
zip_names = zip_file.namelist()
if len(zip_names) == 1:
f = zip_file.open(zip_names.pop())
else:
raise ValueError('ZIP file {} error. Only one file per ZIP.'
.format(path))
else:
msg = 'Unrecognized compression type: {}'.format(compression)
raise ValueError(msg)
yield f
f.close()
def assert_almost_equal(left, right, check_exact=False,
check_dtype='equiv', check_less_precise=False,
**kwargs):
if isinstance(left, pd.Index):
return assert_index_equal(left, right, check_exact=check_exact,
exact=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
elif isinstance(left, pd.Series):
return assert_series_equal(left, right, check_exact=check_exact,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
elif isinstance(left, pd.DataFrame):
return assert_frame_equal(left, right, check_exact=check_exact,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
else:
if check_dtype:
if is_number(left) and is_number(right):
pass
elif is_bool(left) and is_bool(right):
pass
else:
if (isinstance(left, np.ndarray) or
isinstance(right, np.ndarray)):
obj = 'numpy array'
else:
obj = 'Input'
assert_class_equal(left, right, obj=obj)
return _testing.assert_almost_equal(
left, right,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
def _check_isinstance(left, right, cls):
err_msg = "{name} Expected type {exp_type}, found {act_type} instead"
cls_name = cls.__name__
if not isinstance(left, cls):
raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
act_type=type(left)))
if not isinstance(right, cls):
raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
act_type=type(right)))
def assert_dict_equal(left, right, compare_keys=True):
_check_isinstance(left, right, dict)
return _testing.assert_dict_equal(left, right, compare_keys=compare_keys)
def randbool(size=(), p=0.5):
return rand(*size) <= p
RANDS_CHARS = np.array(list(string.ascii_letters + string.digits),
dtype=(np.str_, 1))
RANDU_CHARS = np.array(list(u("").join(map(unichr, lrange(1488, 1488 + 26))) +
string.digits), dtype=(np.unicode_, 1))
def rands_array(nchars, size, dtype='O'):
retval = (np.random.choice(RANDS_CHARS, size=nchars * np.prod(size))
.view((np.str_, nchars)).reshape(size))
if dtype is None:
return retval
else:
return retval.astype(dtype)
def randu_array(nchars, size, dtype='O'):
retval = (np.random.choice(RANDU_CHARS, size=nchars * np.prod(size))
.view((np.unicode_, nchars)).reshape(size))
if dtype is None:
return retval
else:
return retval.astype(dtype)
def rands(nchars):
return ''.join(np.random.choice(RANDS_CHARS, nchars))
def randu(nchars):
return ''.join(np.random.choice(RANDU_CHARS, nchars))
def close(fignum=None):
from matplotlib.pyplot import get_fignums, close as _close
if fignum is None:
for fignum in get_fignums():
_close(fignum)
else:
_close(fignum)
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, stderr=subprocess.PIPE,
*popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd, output=output)
return output
def _default_locale_getter():
try:
raw_locales = check_output(['locale -a'], shell=True)
except subprocess.CalledProcessError as e:
raise type(e)("{exception}, the 'locale -a' command cannot be found "
"on your system".format(exception=e))
return raw_locales
def get_locales(prefix=None, normalize=True,
locale_getter=_default_locale_getter):
try:
raw_locales = locale_getter()
except Exception:
return None
try:
raw_locales = raw_locales.split(b'\n')
out_locales = []
for x in raw_locales:
if PY3:
out_locales.append(str(
x, encoding=pd.options.display.encoding))
else:
out_locales.append(str(x))
except TypeError:
pass
if prefix is None:
return _valid_locales(out_locales, normalize)
found = re.compile('{prefix}.*'.format(prefix=prefix)) \
.findall('\n'.join(out_locales))
return _valid_locales(found, normalize)
@contextmanager
def set_locale(new_locale, lc_var=locale.LC_ALL):
current_locale = locale.getlocale()
try:
locale.setlocale(lc_var, new_locale)
try:
normalized_locale = locale.getlocale()
except ValueError:
yield new_locale
else:
if com._all_not_none(*normalized_locale):
yield '.'.join(normalized_locale)
else:
yield new_locale
finally:
locale.setlocale(lc_var, current_locale)
def _can_set_locale(lc):
try:
with set_locale(lc):
pass
except locale.Error:
return False
else:
return True
def _valid_locales(locales, normalize):
if normalize:
normalizer = lambda x: locale.normalize(x.strip())
else:
normalizer = lambda x: x.strip()
return list(filter(_can_set_locale, map(normalizer, locales)))
def capture_stdout(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
sys.stdout = StringIO()
f(*args, **kwargs)
finally:
sys.stdout = sys.__stdout__
return wrapper
def capture_stderr(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
sys.stderr = StringIO()
f(*args, **kwargs)
finally:
sys.stderr = sys.__stderr__
return wrapper
def debug(f, *args, **kwargs):
from pdb import Pdb as OldPdb
try:
from IPython.core.debugger import Pdb
kw = dict(color_scheme='Linux')
except ImportError:
Pdb = OldPdb
kw = {}
pdb = Pdb(**kw)
return pdb.runcall(f, *args, **kwargs)
def pudebug(f, *args, **kwargs):
import pudb
return pudb.runcall(f, *args, **kwargs)
def set_trace():
from IPython.core.debugger import Pdb
try:
Pdb(color_scheme='Linux').set_trace(sys._getframe().f_back)
except Exception:
from pdb import Pdb as OldPdb
OldPdb().set_trace(sys._getframe().f_back)
@contextmanager
def ensure_clean(filename=None, return_filelike=False):
filename = filename or ''
fd = None
if return_filelike:
f = tempfile.TemporaryFile(suffix=filename)
try:
yield f
finally:
f.close()
else:
if len(os.path.dirname(filename)):
raise ValueError("Can't pass a qualified name to ensure_clean()")
try:
fd, filename = tempfile.mkstemp(suffix=filename)
except UnicodeEncodeError:
import pytest
pytest.skip('no unicode file names on this system')
try:
yield filename
finally:
try:
os.close(fd)
except Exception as e:
print("Couldn't close file descriptor: {fdesc} (file: {fname})"
.format(fdesc=fd, fname=filename))
try:
if os.path.exists(filename):
os.remove(filename)
except Exception as e:
print("Exception on removing file: {error}".format(error=e))
def get_data_path(f=''):
# get our callers file
_, filename, _, _, _, _ = inspect.getouterframes(inspect.currentframe())[1]
base_dir = os.path.abspath(os.path.dirname(filename))
return os.path.join(base_dir, 'data', f)
# -----------------------------------------------------------------------------
# Comparators
def equalContents(arr1, arr2):
return frozenset(arr1) == frozenset(arr2)
def assert_index_equal(left, right, exact='equiv', check_names=True,
check_less_precise=False, check_exact=True,
check_categorical=True, obj='Index'):
def _check_types(l, r, obj='Index'):
if exact:
assert_class_equal(left, right, exact=exact, obj=obj)
assert_attr_equal('dtype', l, r, obj=obj)
# allow string-like to have different inferred_types
if l.inferred_type in ('string', 'unicode'):
assert r.inferred_type in ('string', 'unicode')
else:
assert_attr_equal('inferred_type', l, r, obj=obj)
def _get_ilevel_values(index, level):
# accept level number only
unique = index.levels[level]
labels = index.labels[level]
filled = take_1d(unique.values, labels, fill_value=unique._na_value)
values = unique._shallow_copy(filled, name=index.names[level])
return values
# instance validation
_check_isinstance(left, right, Index)
# class / dtype comparison
_check_types(left, right, obj=obj)
# level comparison
if left.nlevels != right.nlevels:
msg1 = '{obj} levels are different'.format(obj=obj)
msg2 = '{nlevels}, {left}'.format(nlevels=left.nlevels, left=left)
msg3 = '{nlevels}, {right}'.format(nlevels=right.nlevels, right=right)
raise_assert_detail(obj, msg1, msg2, msg3)
# length comparison
if len(left) != len(right):
msg1 = '{obj} length are different'.format(obj=obj)
msg2 = '{length}, {left}'.format(length=len(left), left=left)
msg3 = '{length}, {right}'.format(length=len(right), right=right)
raise_assert_detail(obj, msg1, msg2, msg3)
# MultiIndex special comparison for little-friendly error messages
if left.nlevels > 1:
for level in range(left.nlevels):
# cannot use get_level_values here because it can change dtype
llevel = _get_ilevel_values(left, level)
rlevel = _get_ilevel_values(right, level)
lobj = 'MultiIndex level [{level}]'.format(level=level)
assert_index_equal(llevel, rlevel,
exact=exact, check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact, obj=lobj)
# get_level_values may change dtype
_check_types(left.levels[level], right.levels[level], obj=obj)
if check_exact:
if not left.equals(right):
diff = np.sum((left.values != right.values)
.astype(int)) * 100.0 / len(left)
msg = '{obj} values are different ({pct} %)'.format(
obj=obj, pct=np.round(diff, 5))
raise_assert_detail(obj, msg, left, right)
else:
_testing.assert_almost_equal(left.values, right.values,
check_less_precise=check_less_precise,
check_dtype=exact,
obj=obj, lobj=left, robj=right)
# metadata comparison
if check_names:
assert_attr_equal('names', left, right, obj=obj)
if isinstance(left, pd.PeriodIndex) or isinstance(right, pd.PeriodIndex):
assert_attr_equal('freq', left, right, obj=obj)
if (isinstance(left, pd.IntervalIndex) or
isinstance(right, pd.IntervalIndex)):
assert_attr_equal('closed', left, right, obj=obj)
if check_categorical:
if is_categorical_dtype(left) or is_categorical_dtype(right):
assert_categorical_equal(left.values, right.values,
obj='{obj} category'.format(obj=obj))
def assert_class_equal(left, right, exact=True, obj='Input'):
def repr_class(x):
if isinstance(x, Index):
# return Index as it is to include values in the error message
return x
try:
return x.__class__.__name__
except AttributeError:
return repr(type(x))
if exact == 'equiv':
if type(left) != type(right):
# allow equivalence of Int64Index/RangeIndex
types = set([type(left).__name__, type(right).__name__])
if len(types - set(['Int64Index', 'RangeIndex'])):
msg = '{obj} classes are not equivalent'.format(obj=obj)
raise_assert_detail(obj, msg, repr_class(left),
repr_class(right))
elif exact:
if type(left) != type(right):
msg = '{obj} classes are different'.format(obj=obj)
raise_assert_detail(obj, msg, repr_class(left),
repr_class(right))
def assert_attr_equal(attr, left, right, obj='Attributes'):
left_attr = getattr(left, attr)
right_attr = getattr(right, attr)
if left_attr is right_attr:
return True
elif (is_number(left_attr) and np.isnan(left_attr) and
is_number(right_attr) and np.isnan(right_attr)):
# np.nan
return True
try:
result = left_attr == right_attr
except TypeError:
# datetimetz on rhs may raise TypeError
result = False
if not isinstance(result, bool):
result = result.all()
if result:
return True
else:
msg = 'Attribute "{attr}" are different'.format(attr=attr)
raise_assert_detail(obj, msg, left_attr, right_attr)
def assert_is_valid_plot_return_object(objs):
import matplotlib.pyplot as plt
if isinstance(objs, (pd.Series, np.ndarray)):
for el in objs.ravel():
msg = ('one of \'objs\' is not a matplotlib Axes instance, type '
'encountered {name!r}').format(name=el.__class__.__name__)
assert isinstance(el, (plt.Axes, dict)), msg
else:
assert isinstance(objs, (plt.Artist, tuple, dict)), \
('objs is neither an ndarray of Artist instances nor a '
'single Artist instance, tuple, or dict, "objs" is a {name!r}'
).format(name=objs.__class__.__name__)
def isiterable(obj):
return hasattr(obj, '__iter__')
def is_sorted(seq):
if isinstance(seq, (Index, Series)):
seq = seq.values
# sorting does not change precisions
return assert_numpy_array_equal(seq, np.sort(np.array(seq)))
def assert_categorical_equal(left, right, check_dtype=True,
obj='Categorical', check_category_order=True):
_check_isinstance(left, right, Categorical)
if check_category_order:
assert_index_equal(left.categories, right.categories,
obj='{obj}.categories'.format(obj=obj))
assert_numpy_array_equal(left.codes, right.codes,
check_dtype=check_dtype,
obj='{obj}.codes'.format(obj=obj))
else:
assert_index_equal(left.categories.sort_values(),
right.categories.sort_values(),
obj='{obj}.categories'.format(obj=obj))
assert_index_equal(left.categories.take(left.codes),
right.categories.take(right.codes),
obj='{obj}.values'.format(obj=obj))
assert_attr_equal('ordered', left, right, obj=obj)
def raise_assert_detail(obj, message, left, right, diff=None):
if isinstance(left, np.ndarray):
left = pprint_thing(left)
elif is_categorical_dtype(left):
left = repr(left)
if isinstance(right, np.ndarray):
right = pprint_thing(right)
elif is_categorical_dtype(right):
right = repr(right)
msg = """{obj} are different
{message}
[left]: {left}
[right]: {right}""".format(obj=obj, message=message, left=left, right=right)
if diff is not None:
msg += "\n[diff]: {diff}".format(diff=diff)
raise AssertionError(msg)
def assert_numpy_array_equal(left, right, strict_nan=False,
check_dtype=True, err_msg=None,
obj='numpy array', check_same=None):
# instance validation
# Show a detailed error message when classes are different
assert_class_equal(left, right, obj=obj)
# both classes must be an np.ndarray
_check_isinstance(left, right, np.ndarray)
def _get_base(obj):
return obj.base if getattr(obj, 'base', None) is not None else obj
left_base = _get_base(left)
right_base = _get_base(right)
if check_same == 'same':
if left_base is not right_base:
msg = "{left!r} is not {right!r}".format(
left=left_base, right=right_base)
raise AssertionError(msg)
elif check_same == 'copy':
if left_base is right_base:
msg = "{left!r} is {right!r}".format(
left=left_base, right=right_base)
raise AssertionError(msg)
def _raise(left, right, err_msg):
if err_msg is None:
if left.shape != right.shape:
raise_assert_detail(obj, '{obj} shapes are different'
.format(obj=obj), left.shape, right.shape)
diff = 0
for l, r in zip(left, right):
# count up differences
if not array_equivalent(l, r, strict_nan=strict_nan):
diff += 1
diff = diff * 100.0 / left.size
msg = '{obj} values are different ({pct} %)'.format(
obj=obj, pct=np.round(diff, 5))
raise_assert_detail(obj, msg, left, right)
raise AssertionError(err_msg)
# compare shape and values
if not array_equivalent(left, right, strict_nan=strict_nan):
_raise(left, right, err_msg)
if check_dtype:
if isinstance(left, np.ndarray) and isinstance(right, np.ndarray):
assert_attr_equal('dtype', left, right, obj=obj)
return True
def assert_extension_array_equal(left, right):
assert isinstance(left, ExtensionArray)
assert left.dtype == right.dtype
left_na = left.isna()
right_na = right.isna()
assert_numpy_array_equal(left_na, right_na)
left_valid = left[~left_na].astype(object)
right_valid = right[~right_na].astype(object)
assert_numpy_array_equal(left_valid, right_valid)
# This could be refactored to use the NDFrame.equals method
def assert_series_equal(left, right, check_dtype=True,
check_index_type='equiv',
check_series_type=True,
check_less_precise=False,
check_names=True,
check_exact=False,
check_datetimelike_compat=False,
check_categorical=True,
obj='Series'):
# instance validation
_check_isinstance(left, right, Series)
if check_series_type:
# ToDo: There are some tests using rhs is sparse
# lhs is dense. Should use assert_class_equal in future
assert isinstance(left, type(right))
# assert_class_equal(left, right, obj=obj)
# length comparison
if len(left) != len(right):
msg1 = '{len}, {left}'.format(len=len(left), left=left.index)
msg2 = '{len}, {right}'.format(len=len(right), right=right.index)
raise_assert_detail(obj, 'Series length are different', msg1, msg2)
# index comparison
assert_index_equal(left.index, right.index, exact=check_index_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.index'.format(obj=obj))
if check_dtype:
# We want to skip exact dtype checking when `check_categorical`
# is False. We'll still raise if only one is a `Categorical`,
if (is_categorical_dtype(left) and is_categorical_dtype(right) and
not check_categorical):
pass
else:
assert_attr_equal('dtype', left, right)
if check_exact:
assert_numpy_array_equal(left.get_values(), right.get_values(),
check_dtype=check_dtype,
obj='{obj}'.format(obj=obj),)
elif check_datetimelike_compat:
if (is_datetimelike_v_numeric(left, right) or
is_datetimelike_v_object(left, right) or
needs_i8_conversion(left) or
needs_i8_conversion(right)):
if not Index(left.values).equals(Index(right.values)):
msg = ('[datetimelike_compat=True] {left} is not equal to '
'{right}.').format(left=left.values, right=right.values)
raise AssertionError(msg)
else:
assert_numpy_array_equal(left.get_values(), right.get_values(),
check_dtype=check_dtype)
elif is_interval_dtype(left) or is_interval_dtype(right):
left = pd.IntervalIndex(left)
right = pd.IntervalIndex(right)
assert_index_equal(left, right, obj='{obj}.index'.format(obj=obj))
else:
_testing.assert_almost_equal(left.get_values(), right.get_values(),
check_less_precise=check_less_precise,
check_dtype=check_dtype,
obj='{obj}'.format(obj=obj))
if check_names:
assert_attr_equal('name', left, right, obj=obj)
if check_categorical:
if is_categorical_dtype(left) or is_categorical_dtype(right):
assert_categorical_equal(left.values, right.values,
obj='{obj} category'.format(obj=obj))
def assert_frame_equal(left, right, check_dtype=True,
check_index_type='equiv',
check_column_type='equiv',
check_frame_type=True,
check_less_precise=False,
check_names=True,
by_blocks=False,
check_exact=False,
check_datetimelike_compat=False,
check_categorical=True,
check_like=False,
obj='DataFrame'):
_check_isinstance(left, right, DataFrame)
if check_frame_type:
assert isinstance(left, type(right))
if left.shape != right.shape:
raise_assert_detail(obj,
'DataFrame shape mismatch',
'{shape!r}'.format(shape=left.shape),
'{shape!r}'.format(shape=right.shape))
if check_like:
left, right = left.reindex_like(right), right
assert_index_equal(left.index, right.index, exact=check_index_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.index'.format(obj=obj))
assert_index_equal(left.columns, right.columns, exact=check_column_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.columns'.format(obj=obj))
if by_blocks:
rblocks = right._to_dict_of_blocks()
lblocks = left._to_dict_of_blocks()
for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
assert dtype in lblocks
assert dtype in rblocks
assert_frame_equal(lblocks[dtype], rblocks[dtype],
check_dtype=check_dtype, obj='DataFrame.blocks')
else:
for i, col in enumerate(left.columns):
assert col in right
lcol = left.iloc[:, i]
rcol = right.iloc[:, i]
assert_series_equal(
lcol, rcol, check_dtype=check_dtype,
check_index_type=check_index_type,
check_less_precise=check_less_precise,
check_exact=check_exact, check_names=check_names,
check_datetimelike_compat=check_datetimelike_compat,
check_categorical=check_categorical,
obj='DataFrame.iloc[:, {idx}]'.format(idx=i))
def assert_panel_equal(left, right,
check_dtype=True,
check_panel_type=False,
check_less_precise=False,
check_names=False,
by_blocks=False,
obj='Panel'):
if check_panel_type:
assert_class_equal(left, right, obj=obj)
for axis in left._AXIS_ORDERS:
left_ind = getattr(left, axis)
right_ind = getattr(right, axis)
assert_index_equal(left_ind, right_ind, check_names=check_names)
if by_blocks:
rblocks = right._to_dict_of_blocks()
lblocks = left._to_dict_of_blocks()
for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
assert dtype in lblocks
assert dtype in rblocks
array_equivalent(lblocks[dtype].values, rblocks[dtype].values)
else:
for i, item in enumerate(left._get_axis(0)):
msg = "non-matching item (right) '{item}'".format(item=item)
assert item in right, msg
litem = left.iloc[i]
ritem = right.iloc[i]
assert_frame_equal(litem, ritem,
check_less_precise=check_less_precise,
check_names=check_names)
for i, item in enumerate(right._get_axis(0)):
msg = "non-matching item (left) '{item}'".format(item=item)
assert item in left, msg
def assert_sp_array_equal(left, right, check_dtype=True):
_check_isinstance(left, right, pd.SparseArray)
assert_numpy_array_equal(left.sp_values, right.sp_values,
check_dtype=check_dtype)
assert isinstance(left.sp_index, pd._libs.sparse.SparseIndex)
assert isinstance(right.sp_index, pd._libs.sparse.SparseIndex)
if not left.sp_index.equals(right.sp_index):
raise_assert_detail('SparseArray.index', 'index are not equal',
left.sp_index, right.sp_index)
assert_attr_equal('fill_value', left, right)
if check_dtype:
assert_attr_equal('dtype', left, right)
assert_numpy_array_equal(left.values, right.values,
check_dtype=check_dtype)
def assert_sp_series_equal(left, right, check_dtype=True, exact_indices=True,
check_series_type=True, check_names=True,
obj='SparseSeries'):
_check_isinstance(left, right, pd.SparseSeries)
if check_series_type:
assert_class_equal(left, right, obj=obj)
assert_index_equal(left.index, right.index,
obj='{obj}.index'.format(obj=obj))
assert_sp_array_equal(left.block.values, right.block.values)
if check_names:
assert_attr_equal('name', left, right)
if check_dtype:
assert_attr_equal('dtype', left, right)
assert_numpy_array_equal(left.values, right.values)
def assert_sp_frame_equal(left, right, check_dtype=True, exact_indices=True,
check_frame_type=True, obj='SparseDataFrame'):
_check_isinstance(left, right, pd.SparseDataFrame)
if check_frame_type:
assert_class_equal(left, right, obj=obj)
assert_index_equal(left.index, right.index,
obj='{obj}.index'.format(obj=obj))
assert_index_equal(left.columns, right.columns,
obj='{obj}.columns'.format(obj=obj))
for col, series in compat.iteritems(left):
assert (col in right)
if exact_indices:
assert_sp_series_equal(series, right[col],
check_dtype=check_dtype)
else:
assert_series_equal(series.to_dense(), right[col].to_dense(),
check_dtype=check_dtype)
assert_attr_equal('default_fill_value', left, right, obj=obj)
for col in right:
assert (col in left)
def assert_contains_all(iterable, dic):
for k in iterable:
assert k in dic, "Did not contain item: '{key!r}'".format(key=k)
def assert_copy(iter1, iter2, **eql_kwargs):
for elem1, elem2 in zip(iter1, iter2):
assert_almost_equal(elem1, elem2, **eql_kwargs)
msg = ("Expected object {obj1!r} and object {obj2!r} to be "
"different objects, but they were the same object."
).format(obj1=type(elem1), obj2=type(elem2))
assert elem1 is not elem2, msg
def getCols(k):
return string.ascii_uppercase[:k]
def getArangeMat():
return np.arange(N * K).reshape((N, K))
def makeStringIndex(k=10, name=None):
return Index(rands_array(nchars=10, size=k), name=name)
def makeUnicodeIndex(k=10, name=None):
return Index(randu_array(nchars=10, size=k), name=name)
def makeCategoricalIndex(k=10, n=3, name=None, **kwargs):
x = rands_array(nchars=4, size=n)
return CategoricalIndex(np.random.choice(x, k), name=name, **kwargs)
def makeIntervalIndex(k=10, name=None, **kwargs):
x = np.linspace(0, 100, num=(k + 1))
return IntervalIndex.from_breaks(x, name=name, **kwargs)
def makeBoolIndex(k=10, name=None):
if k == 1:
return Index([True], name=name)
elif k == 2:
return Index([False, True], name=name)
return Index([False, True] + [False] * (k - 2), name=name)
def makeIntIndex(k=10, name=None):
return Index(lrange(k), name=name)
def makeUIntIndex(k=10, name=None):
return Index([2**63 + i for i in lrange(k)], name=name)
def makeRangeIndex(k=10, name=None, **kwargs):
return RangeIndex(0, k, 1, name=name, **kwargs)
def makeFloatIndex(k=10, name=None):
values = sorted(np.random.random_sample(k)) - np.random.random_sample(1)
return Index(values * (10 ** np.random.randint(0, 9)), name=name)
def makeDateIndex(k=10, freq='B', name=None, **kwargs):
dt = datetime(2000, 1, 1)
dr = bdate_range(dt, periods=k, freq=freq, name=name)
return DatetimeIndex(dr, name=name, **kwargs)
def makeTimedeltaIndex(k=10, freq='D', name=None, **kwargs):
return TimedeltaIndex(start='1 day', periods=k, freq=freq,
name=name, **kwargs)
def makePeriodIndex(k=10, name=None, **kwargs):
dt = datetime(2000, 1, 1)
dr = PeriodIndex(start=dt, periods=k, freq='B', name=name, **kwargs)
return dr
def makeMultiIndex(k=10, names=None, **kwargs):
return MultiIndex.from_product(
(('foo', 'bar'), (1, 2)), names=names, **kwargs)
def all_index_generator(k=10):
all_make_index_funcs = [makeIntIndex, makeFloatIndex, makeStringIndex,
makeUnicodeIndex, makeDateIndex, makePeriodIndex,
makeTimedeltaIndex, makeBoolIndex, makeRangeIndex,
makeIntervalIndex,
makeCategoricalIndex]
for make_index_func in all_make_index_funcs:
yield make_index_func(k=k)
def index_subclass_makers_generator():
make_index_funcs = [
makeDateIndex, makePeriodIndex,
makeTimedeltaIndex, makeRangeIndex,
makeIntervalIndex, makeCategoricalIndex,
makeMultiIndex
]
for make_index_func in make_index_funcs:
yield make_index_func
def all_timeseries_index_generator(k=10):
make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex]
for make_index_func in make_index_funcs:
yield make_index_func(k=k)
def makeFloatSeries(name=None):
index = makeStringIndex(N)
return Series(randn(N), index=index, name=name)
def makeStringSeries(name=None):
index = makeStringIndex(N)
return Series(randn(N), index=index, name=name)
def makeObjectSeries(name=None):
dateIndex = makeDateIndex(N)
dateIndex = Index(dateIndex, dtype=object)
index = makeStringIndex(N)
return Series(dateIndex, index=index, name=name)
def getSeriesData():
index = makeStringIndex(N)
return {c: Series(randn(N), index=index) for c in getCols(K)}
def makeTimeSeries(nper=None, freq='B', name=None):
if nper is None:
nper = N
return Series(randn(nper), index=makeDateIndex(nper, freq=freq), name=name)
def makePeriodSeries(nper=None, name=None):
if nper is None:
nper = N
return Series(randn(nper), index=makePeriodIndex(nper), name=name)
def getTimeSeriesData(nper=None, freq='B'):
return {c: makeTimeSeries(nper, freq) for c in getCols(K)}
def getPeriodData(nper=None):
return {c: makePeriodSeries(nper) for c in getCols(K)}
def makeTimeDataFrame(nper=None, freq='B'):
data = getTimeSeriesData(nper, freq)
return DataFrame(data)
def makeDataFrame():
data = getSeriesData()
return DataFrame(data)
def getMixedTypeDict():
index = Index(['a', 'b', 'c', 'd', 'e'])
data = {
'A': [0., 1., 2., 3., 4.],
'B': [0., 1., 0., 1., 0.],
'C': ['foo1', 'foo2', 'foo3', 'foo4', 'foo5'],
'D': bdate_range('1/1/2009', periods=5)
}
return index, data
def makeMixedDataFrame():
return DataFrame(getMixedTypeDict()[1])
def makePeriodFrame(nper=None):
data = getPeriodData(nper)
return DataFrame(data)
def makePanel(nper=None):
with warnings.catch_warnings(record=True):
cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]]
data = {c: makeTimeDataFrame(nper) for c in cols}
return Panel.fromDict(data)
def makePeriodPanel(nper=None):
with warnings.catch_warnings(record=True):
cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]]
data = {c: makePeriodFrame(nper) for c in cols}
return Panel.fromDict(data)
def makeCustomIndex(nentries, nlevels, prefix='#', names=False, ndupe_l=None,
idx_type=None):
if ndupe_l is None:
ndupe_l = [1] * nlevels
assert (is_sequence(ndupe_l) and len(ndupe_l) <= nlevels)
assert (names is None or names is False or
names is True or len(names) is nlevels)
assert idx_type is None or \
(idx_type in ('i', 'f', 's', 'u', 'dt', 'p', 'td') and nlevels == 1)
if names is True:
names = [prefix + str(i) for i in range(nlevels)]
if names is False:
names = None
if isinstance(names, compat.string_types) and nlevels == 1:
names = [names]
idx_func = dict(i=makeIntIndex, f=makeFloatIndex,
s=makeStringIndex, u=makeUnicodeIndex,
dt=makeDateIndex, td=makeTimedeltaIndex,
p=makePeriodIndex).get(idx_type)
if idx_func:
idx = idx_func(nentries)
if names:
idx.name = names[0]
return idx
elif idx_type is not None:
raise ValueError('"{idx_type}" is not a legal value for `idx_type`, '
'use "i"/"f"/"s"/"u"/"dt/"p"/"td".'
.format(idx_type=idx_type))
if len(ndupe_l) < nlevels:
ndupe_l.extend([1] * (nlevels - len(ndupe_l)))
assert len(ndupe_l) == nlevels
assert all(x > 0 for x in ndupe_l)
tuples = []
for i in range(nlevels):
def keyfunc(x):
import re
numeric_tuple = re.sub(r"[^\d_]_?", "", x).split("_")
return lmap(int, numeric_tuple)
# build a list of lists to create the index from
div_factor = nentries // ndupe_l[i] + 1
cnt = Counter()
for j in range(div_factor):
label = '{prefix}_l{i}_g{j}'.format(prefix=prefix, i=i, j=j)
cnt[label] = ndupe_l[i]
# cute Counter trick
result = list(sorted(cnt.elements(), key=keyfunc))[:nentries]
tuples.append(result)
tuples = lzip(*tuples)
# convert tuples to index
if nentries == 1:
# we have a single level of tuples, i.e. a regular Index
index = Index(tuples[0], name=names[0])
elif nlevels == 1:
name = None if names is None else names[0]
index = Index((x[0] for x in tuples), name=name)
else:
index = MultiIndex.from_tuples(tuples, names=names)
return index
def makeCustomDataframe(nrows, ncols, c_idx_names=True, r_idx_names=True,
c_idx_nlevels=1, r_idx_nlevels=1, data_gen_f=None,
c_ndupe_l=None, r_ndupe_l=None, dtype=None,
c_idx_type=None, r_idx_type=None):
assert c_idx_nlevels > 0
assert r_idx_nlevels > 0
assert r_idx_type is None or \
(r_idx_type in ('i', 'f', 's',
'u', 'dt', 'p', 'td') and r_idx_nlevels == 1)
assert c_idx_type is None or \
(c_idx_type in ('i', 'f', 's',
'u', 'dt', 'p', 'td') and c_idx_nlevels == 1)
columns = makeCustomIndex(ncols, nlevels=c_idx_nlevels, prefix='C',
names=c_idx_names, ndupe_l=c_ndupe_l,
idx_type=c_idx_type)
index = makeCustomIndex(nrows, nlevels=r_idx_nlevels, prefix='R',
names=r_idx_names, ndupe_l=r_ndupe_l,
idx_type=r_idx_type)
# by default, generate data based on location
if data_gen_f is None:
data_gen_f = lambda r, c: "R{rows}C{cols}".format(rows=r, cols=c)
data = [[data_gen_f(r, c) for c in range(ncols)] for r in range(nrows)]
return DataFrame(data, index, columns, dtype=dtype)
def _create_missing_idx(nrows, ncols, density, random_state=None):
if random_state is None:
random_state = np.random
else:
random_state = np.random.RandomState(random_state)
# below is cribbed from scipy.sparse
size = int(np.round((1 - density) * nrows * ncols))
# generate a few more to ensure unique values
min_rows = 5
fac = 1.02
extra_size = min(size + min_rows, fac * size)
def _gen_unique_rand(rng, _extra_size):
ind = rng.rand(int(_extra_size))
return np.unique(np.floor(ind * nrows * ncols))[:size]
ind = _gen_unique_rand(random_state, extra_size)
while ind.size < size:
extra_size *= 1.05
ind = _gen_unique_rand(random_state, extra_size)
j = np.floor(ind * 1. / nrows).astype(int)
i = (ind - j * nrows).astype(int)
return i.tolist(), j.tolist()
def makeMissingCustomDataframe(nrows, ncols, density=.9, random_state=None,
c_idx_names=True, r_idx_names=True,
c_idx_nlevels=1, r_idx_nlevels=1,
data_gen_f=None,
c_ndupe_l=None, r_ndupe_l=None, dtype=None,
c_idx_type=None, r_idx_type=None):
df = makeCustomDataframe(nrows, ncols, c_idx_names=c_idx_names,
r_idx_names=r_idx_names,
c_idx_nlevels=c_idx_nlevels,
r_idx_nlevels=r_idx_nlevels,
data_gen_f=data_gen_f,
c_ndupe_l=c_ndupe_l, r_ndupe_l=r_ndupe_l,
dtype=dtype, c_idx_type=c_idx_type,
r_idx_type=r_idx_type)
i, j = _create_missing_idx(nrows, ncols, density, random_state)
df.values[i, j] = np.nan
return df
def makeMissingDataframe(density=.9, random_state=None):
df = makeDataFrame()
i, j = _create_missing_idx(*df.shape, density=density,
random_state=random_state)
df.values[i, j] = np.nan
return df
def add_nans(panel):
I, J, N = panel.shape
for i, item in enumerate(panel.items):
dm = panel[item]
for j, col in enumerate(dm.columns):
dm[col][:i + j] = np.NaN
return panel
def add_nans_panel4d(panel4d):
for l, label in enumerate(panel4d.labels):
panel = panel4d[label]
add_nans(panel)
return panel4d
class TestSubDict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
def optional_args(decorator):
@wraps(decorator)
def wrapper(*args, **kwargs):
def dec(f):
return decorator(f, *args, **kwargs)
is_decorating = not kwargs and len(args) == 1 and callable(args[0])
if is_decorating:
f = args[0]
args = []
return dec(f)
else:
return dec
return wrapper
# skip tests on exceptions with this message
_network_error_messages = (
# 'urlopen error timed out',
# 'timeout: timed out',
# 'socket.timeout: timed out',
'timed out',
'Server Hangup',
'HTTP Error 503: Service Unavailable',
'502: Proxy Error',
'HTTP Error 502: internal error',
'HTTP Error 502',
'HTTP Error 503',
'HTTP Error 403',
'HTTP Error 400',
'Temporary failure in name resolution',
'Name or service not known',
'Connection refused',
'certificate verify',
)
# or this e.errno/e.reason.errno
_network_errno_vals = (
101, # Network is unreachable
111, # Connection refused
110, # Connection timed out
104, # Connection reset Error
54, # Connection reset by peer
60, # urllib.error.URLError: [Errno 60] Connection timed out
)
# Both of the above shouldn't mask real issues such as 404's
# or refused connections (changed DNS).
# But some tests (test_data yahoo) contact incredibly flakey
# servers.
# and conditionally raise on these exception types
_network_error_classes = (IOError, httplib.HTTPException)
if sys.version_info >= (3, 3):
_network_error_classes += (TimeoutError,) # noqa
def can_connect(url, error_classes=_network_error_classes):
try:
with urlopen(url):
pass
except error_classes:
return False
else:
return True
@optional_args
def network(t, url="http://www.google.com",
raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT,
check_before_test=False,
error_classes=_network_error_classes,
skip_errnos=_network_errno_vals,
_skip_on_messages=_network_error_messages,
):
from pytest import skip
t.network = True
@compat.wraps(t)
def wrapper(*args, **kwargs):
if check_before_test and not raise_on_error:
if not can_connect(url, error_classes):
skip()
try:
return t(*args, **kwargs)
except Exception as e:
errno = getattr(e, 'errno', None)
if not errno and hasattr(errno, "reason"):
errno = getattr(e.reason, 'errno', None)
if errno in skip_errnos:
skip("Skipping test due to known errno"
" and error {error}".format(error=e))
try:
e_str = traceback.format_exc(e)
except Exception:
e_str = str(e)
if any(m.lower() in e_str.lower() for m in _skip_on_messages):
skip("Skipping test because exception "
"message is known and error {error}".format(error=e))
if not isinstance(e, error_classes):
raise
if raise_on_error or can_connect(url, error_classes):
raise
else:
skip("Skipping test due to lack of connectivity"
" and error {error}".format(e))
return wrapper
with_connectivity_check = network
class SimpleMock(object):
def __init__(self, obj, *args, **kwds):
assert(len(args) % 2 == 0)
attrs = kwds.get("attrs", {})
for k, v in zip(args[::2], args[1::2]):
# dict comprehensions break 2.6
attrs[k] = v
self.attrs = attrs
self.obj = obj
def __getattribute__(self, name):
attrs = object.__getattribute__(self, "attrs")
obj = object.__getattribute__(self, "obj")
return attrs.get(name, type(obj).__getattribute__(obj, name))
@contextmanager
def stdin_encoding(encoding=None):
import sys
_stdin = sys.stdin
sys.stdin = SimpleMock(sys.stdin, "encoding", encoding)
yield
sys.stdin = _stdin
def assert_raises_regex(_exception, _regexp, _callable=None,
*args, **kwargs):
manager = _AssertRaisesContextmanager(exception=_exception, regexp=_regexp)
if _callable is not None:
with manager:
_callable(*args, **kwargs)
else:
return manager
class _AssertRaisesContextmanager(object):
def __init__(self, exception, regexp=None):
self.exception = exception
if regexp is not None and not hasattr(regexp, "search"):
regexp = re.compile(regexp, re.DOTALL)
self.regexp = regexp
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, trace_back):
expected = self.exception
if not exc_type:
exp_name = getattr(expected, "__name__", str(expected))
raise AssertionError("{name} not raised.".format(name=exp_name))
return self.exception_matches(exc_type, exc_value, trace_back)
def exception_matches(self, exc_type, exc_value, trace_back):
if issubclass(exc_type, self.exception):
if self.regexp is not None:
val = str(exc_value)
if not self.regexp.search(val):
msg = '"{pat}" does not match "{val}"'.format(
pat=self.regexp.pattern, val=val)
e = AssertionError(msg)
raise_with_traceback(e, trace_back)
return True
else:
# Failed, so allow Exception to bubble up.
return False
@contextmanager
def assert_produces_warning(expected_warning=Warning, filter_level="always",
clear=None, check_stacklevel=True):
with warnings.catch_warnings(record=True) as w:
if clear is not None:
# make sure that we are clearning these warnings
# if they have happened before
# to guarantee that we will catch them
if not is_list_like(clear):
clear = [clear]
for m in clear:
try:
m.__warningregistry__.clear()
except Exception:
pass
saw_warning = False
warnings.simplefilter(filter_level)
yield w
extra_warnings = []
for actual_warning in w:
if (expected_warning and issubclass(actual_warning.category,
expected_warning)):
saw_warning = True
if check_stacklevel and issubclass(actual_warning.category,
(FutureWarning,
DeprecationWarning)):
from inspect import getframeinfo, stack
caller = getframeinfo(stack()[2][0])
msg = ("Warning not set with correct stacklevel. "
"File where warning is raised: {actual} != "
"{caller}. Warning message: {message}"
).format(actual=actual_warning.filename,
caller=caller.filename,
message=actual_warning.message)
assert actual_warning.filename == caller.filename, msg
else:
extra_warnings.append(actual_warning.category.__name__)
if expected_warning:
msg = "Did not see expected warning of class {name!r}.".format(
name=expected_warning.__name__)
assert saw_warning, msg
assert not extra_warnings, ("Caused unexpected warning(s): {extra!r}."
).format(extra=extra_warnings)
class RNGContext(object):
def __init__(self, seed):
self.seed = seed
def __enter__(self):
self.start_state = np.random.get_state()
np.random.seed(self.seed)
def __exit__(self, exc_type, exc_value, traceback):
np.random.set_state(self.start_state)
@contextmanager
def use_numexpr(use, min_elements=None):
from pandas.core.computation import expressions as expr
if min_elements is None:
min_elements = expr._MIN_ELEMENTS
olduse = expr._USE_NUMEXPR
oldmin = expr._MIN_ELEMENTS
expr.set_use_numexpr(use)
expr._MIN_ELEMENTS = min_elements
yield
expr._MIN_ELEMENTS = oldmin
expr.set_use_numexpr(olduse)
def test_parallel(num_threads=2, kwargs_list=None):
assert num_threads > 0
has_kwargs_list = kwargs_list is not None
if has_kwargs_list:
assert len(kwargs_list) == num_threads
import threading
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
if has_kwargs_list:
update_kwargs = lambda i: dict(kwargs, **kwargs_list[i])
else:
update_kwargs = lambda i: kwargs
threads = []
for i in range(num_threads):
updated_kwargs = update_kwargs(i)
thread = threading.Thread(target=func, args=args,
kwargs=updated_kwargs)
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return inner
return wrapper
class SubclassedSeries(Series):
_metadata = ['testattr', 'name']
@property
def _constructor(self):
return SubclassedSeries
@property
def _constructor_expanddim(self):
return SubclassedDataFrame
class SubclassedDataFrame(DataFrame):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedDataFrame
@property
def _constructor_sliced(self):
return SubclassedSeries
class SubclassedSparseSeries(pd.SparseSeries):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedSparseSeries
@property
def _constructor_expanddim(self):
return SubclassedSparseDataFrame
class SubclassedSparseDataFrame(pd.SparseDataFrame):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedSparseDataFrame
@property
def _constructor_sliced(self):
return SubclassedSparseSeries
class SubclassedCategorical(Categorical):
@property
def _constructor(self):
return SubclassedCategorical
@contextmanager
def patch(ob, attr, value):
noattr = object() # mark that the attribute never existed
old = getattr(ob, attr, noattr)
setattr(ob, attr, value)
try:
yield
finally:
if old is noattr:
delattr(ob, attr)
else:
setattr(ob, attr, old)
@contextmanager
def set_timezone(tz):
import os
import time
def setTZ(tz):
if tz is None:
try:
del os.environ['TZ']
except KeyError:
pass
else:
os.environ['TZ'] = tz
time.tzset()
orig_tz = os.environ.get('TZ')
setTZ(tz)
try:
yield
finally:
setTZ(orig_tz)
def _make_skipna_wrapper(alternative, skipna_alternative=None):
if skipna_alternative:
def skipna_wrapper(x):
return skipna_alternative(x.values)
else:
def skipna_wrapper(x):
nona = x.dropna()
if len(nona) == 0:
return np.nan
return alternative(nona)
return skipna_wrapper
| true | true |
f72c3bbbbfb56f466b8bb7c5ad7d122e79a30a61 | 22,903 | py | Python | app/venv/lib/python2.7/site-packages/numpy/distutils/mingw32ccompiler.py | anaheino/Ufo-sightings-map | 64af02093f97737cbbdfd8af9e1aeb4d8aa8fcdc | [
"MIT"
] | 652 | 2015-07-26T00:00:17.000Z | 2022-02-24T18:30:04.000Z | app/venv/lib/python2.7/site-packages/numpy/distutils/mingw32ccompiler.py | anaheino/Ufo-sightings-map | 64af02093f97737cbbdfd8af9e1aeb4d8aa8fcdc | [
"MIT"
] | 8 | 2015-09-07T03:38:19.000Z | 2021-05-23T03:18:51.000Z | app/venv/lib/python2.7/site-packages/numpy/distutils/mingw32ccompiler.py | anaheino/Ufo-sightings-map | 64af02093f97737cbbdfd8af9e1aeb4d8aa8fcdc | [
"MIT"
] | 40 | 2015-07-24T19:45:08.000Z | 2021-11-01T14:54:56.000Z | """
Support code for building Python extensions on Windows.
# NT stuff
# 1. Make sure libpython<version>.a exists for gcc. If not, build it.
# 2. Force windows to use gcc (we're struggling with MSVC and g77 support)
# 3. Force windows to use g77
"""
from __future__ import division, absolute_import, print_function
import os
import sys
import subprocess
import re
# Overwrite certain distutils.ccompiler functions:
import numpy.distutils.ccompiler
if sys.version_info[0] < 3:
from . import log
else:
from numpy.distutils import log
# NT stuff
# 1. Make sure libpython<version>.a exists for gcc. If not, build it.
# 2. Force windows to use gcc (we're struggling with MSVC and g77 support)
# --> this is done in numpy/distutils/ccompiler.py
# 3. Force windows to use g77
import distutils.cygwinccompiler
from distutils.version import StrictVersion
from numpy.distutils.ccompiler import gen_preprocess_options, gen_lib_options
from distutils.unixccompiler import UnixCCompiler
from distutils.msvccompiler import get_build_version as get_build_msvc_version
from distutils.errors import (DistutilsExecError, CompileError,
UnknownFileError)
from numpy.distutils.misc_util import (msvc_runtime_library,
get_build_architecture)
# Useful to generate table of symbols from a dll
_START = re.compile(r'\[Ordinal/Name Pointer\] Table')
_TABLE = re.compile(r'^\s+\[([\s*[0-9]*)\] ([a-zA-Z0-9_]*)')
# the same as cygwin plus some additional parameters
class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler):
""" A modified MingW32 compiler compatible with an MSVC built Python.
"""
compiler_type = 'mingw32'
def __init__ (self,
verbose=0,
dry_run=0,
force=0):
distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose,
dry_run, force)
# we need to support 3.2 which doesn't match the standard
# get_versions methods regex
if self.gcc_version is None:
import re
p = subprocess.Popen(['gcc', '-dumpversion'], shell=True,
stdout=subprocess.PIPE)
out_string = p.stdout.read()
p.stdout.close()
result = re.search('(\d+\.\d+)', out_string)
if result:
self.gcc_version = StrictVersion(result.group(1))
# A real mingw32 doesn't need to specify a different entry point,
# but cygwin 2.91.57 in no-cygwin-mode needs it.
if self.gcc_version <= "2.91.57":
entry_point = '--entry _DllMain@12'
else:
entry_point = ''
if self.linker_dll == 'dllwrap':
# Commented out '--driver-name g++' part that fixes weird
# g++.exe: g++: No such file or directory
# error (mingw 1.0 in Enthon24 tree, gcc-3.4.5).
# If the --driver-name part is required for some environment
# then make the inclusion of this part specific to that
# environment.
self.linker = 'dllwrap' # --driver-name g++'
elif self.linker_dll == 'gcc':
self.linker = 'g++'
p = subprocess.Popen(['gcc', '--version'], shell=True,
stdout=subprocess.PIPE)
out_string = p.stdout.read()
p.stdout.close()
# Before build with MinGW-W64 generate the python import library
# with gendef and dlltool according to the MingW-W64 FAQ.
# Use the MinGW-W64 provided msvc runtime import libraries.
# Don't call build_import_library() and build_msvcr_library.
if 'MinGW-W64' not in str(out_string):
# **changes: eric jones 4/11/01
# 1. Check for import library on Windows. Build if it doesn't
# exist.
build_import_library()
# Check for custom msvc runtime library on Windows. Build if it
# doesn't exist.
msvcr_success = build_msvcr_library()
msvcr_dbg_success = build_msvcr_library(debug=True)
if msvcr_success or msvcr_dbg_success:
# add preprocessor statement for using customized msvcr lib
self.define_macro('NPY_MINGW_USE_CUSTOM_MSVCR')
# Define the MSVC version as hint for MinGW
msvcr_version = '0x%03i0' % int(msvc_runtime_library().lstrip('msvcr'))
self.define_macro('__MSVCRT_VERSION__', msvcr_version)
# MS_WIN64 should be defined when building for amd64 on windows,
# but python headers define it only for MS compilers, which has all
# kind of bad consequences, like using Py_ModuleInit4 instead of
# Py_ModuleInit4_64, etc... So we add it here
if get_build_architecture() == 'AMD64':
if self.gcc_version < "4.0":
self.set_executables(
compiler='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0 -Wall',
compiler_so='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0'
' -Wall -Wstrict-prototypes',
linker_exe='gcc -g -mno-cygwin',
linker_so='gcc -g -mno-cygwin -shared')
else:
# gcc-4 series releases do not support -mno-cygwin option
self.set_executables(
compiler='gcc -march=x86-64 -mtune=generic -DMS_WIN64'
' -O2 -msse2 -Wall',
compiler_so='gcc -march=x86-64 -mtune=generic -DMS_WIN64'
' -O2 -msse2 -Wall -Wstrict-prototypes',
linker_exe='gcc',
linker_so='gcc -shared -Wl,-gc-sections -Wl,-s')
else:
if self.gcc_version <= "3.0.0":
self.set_executables(
compiler='gcc -mno-cygwin -O2 -w',
compiler_so='gcc -mno-cygwin -mdll -O2 -w'
' -Wstrict-prototypes',
linker_exe='g++ -mno-cygwin',
linker_so='%s -mno-cygwin -mdll -static %s' %
(self.linker, entry_point))
elif self.gcc_version < "4.0":
self.set_executables(
compiler='gcc -mno-cygwin -O2 -Wall',
compiler_so='gcc -mno-cygwin -O2 -Wall'
' -Wstrict-prototypes',
linker_exe='g++ -mno-cygwin',
linker_so='g++ -mno-cygwin -shared')
else:
# gcc-4 series releases do not support -mno-cygwin option i686
# build needs '-mincoming-stack-boundary=2' due to ABI
# incompatibility to Win32 ABI
self.set_executables(
compiler='gcc -O2 -march=core2 -mtune=generic'
' -mfpmath=sse -msse2'
' -mincoming-stack-boundary=2 -Wall',
compiler_so='gcc -O2 -march=core2 -mtune=generic'
' -mfpmath=sse -msse2'
' -mincoming-stack-boundary=2 -Wall'
' -Wstrict-prototypes',
linker_exe='g++ ',
linker_so='g++ -shared -Wl,-gc-sections -Wl,-s')
# added for python2.3 support we can't pass it through set_executables
# because pre 2.2 would fail
self.compiler_cxx = ['g++']
# Maybe we should also append -mthreads, but then the finished dlls
# need another dll (mingwm10.dll see Mingw32 docs) (-mthreads: Support
# thread-safe exception handling on `Mingw32')
# no additional libraries needed
#self.dll_libraries=[]
return
# __init__ ()
def link(self,
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
export_symbols = None,
debug=0,
extra_preargs=None,
extra_postargs=None,
build_temp=None,
target_lang=None):
# Include the appropiate MSVC runtime library if Python was built
# with MSVC >= 7.0 (MinGW standard is msvcrt)
runtime_library = msvc_runtime_library()
if runtime_library:
if not libraries:
libraries = []
libraries.append(runtime_library)
args = (self,
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
None, #export_symbols, we do this in our def-file
debug,
extra_preargs,
extra_postargs,
build_temp,
target_lang)
if self.gcc_version < "3.0.0":
func = distutils.cygwinccompiler.CygwinCCompiler.link
else:
func = UnixCCompiler.link
func(*args[:func.__code__.co_argcount])
return
def object_filenames (self,
source_filenames,
strip_dir=0,
output_dir=''):
if output_dir is None: output_dir = ''
obj_names = []
for src_name in source_filenames:
# use normcase to make sure '.rc' is really '.rc' and not '.RC'
(base, ext) = os.path.splitext (os.path.normcase(src_name))
# added these lines to strip off windows drive letters
# without it, .o files are placed next to .c files
# instead of the build directory
drv, base = os.path.splitdrive(base)
if drv:
base = base[1:]
if ext not in (self.src_extensions + ['.rc', '.res']):
raise UnknownFileError(
"unknown file type '%s' (from '%s')" % \
(ext, src_name))
if strip_dir:
base = os.path.basename (base)
if ext == '.res' or ext == '.rc':
# these need to be compiled to object files
obj_names.append (os.path.join (output_dir,
base + ext + self.obj_extension))
else:
obj_names.append (os.path.join (output_dir,
base + self.obj_extension))
return obj_names
# object_filenames ()
def find_python_dll():
maj, min, micro = [int(i) for i in sys.version_info[:3]]
dllname = 'python%d%d.dll' % (maj, min)
print("Looking for %s" % dllname)
# We can't do much here:
# - find it in python main dir
# - in system32,
# - ortherwise (Sxs), I don't know how to get it.
lib_dirs = []
lib_dirs.append(sys.prefix)
lib_dirs.append(os.path.join(sys.prefix, 'lib'))
try:
lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'system32'))
except KeyError:
pass
for d in lib_dirs:
dll = os.path.join(d, dllname)
if os.path.exists(dll):
return dll
raise ValueError("%s not found in %s" % (dllname, lib_dirs))
def dump_table(dll):
st = subprocess.Popen(["objdump.exe", "-p", dll], stdout=subprocess.PIPE)
return st.stdout.readlines()
def generate_def(dll, dfile):
"""Given a dll file location, get all its exported symbols and dump them
into the given def file.
The .def file will be overwritten"""
dump = dump_table(dll)
for i in range(len(dump)):
if _START.match(dump[i].decode()):
break
else:
raise ValueError("Symbol table not found")
syms = []
for j in range(i+1, len(dump)):
m = _TABLE.match(dump[j].decode())
if m:
syms.append((int(m.group(1).strip()), m.group(2)))
else:
break
if len(syms) == 0:
log.warn('No symbols found in %s' % dll)
d = open(dfile, 'w')
d.write('LIBRARY %s\n' % os.path.basename(dll))
d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n')
d.write(';DATA PRELOAD SINGLE\n')
d.write('\nEXPORTS\n')
for s in syms:
#d.write('@%d %s\n' % (s[0], s[1]))
d.write('%s\n' % s[1])
d.close()
def find_dll(dll_name):
arch = {'AMD64' : 'amd64',
'Intel' : 'x86'}[get_build_architecture()]
def _find_dll_in_winsxs(dll_name):
# Walk through the WinSxS directory to find the dll.
winsxs_path = os.path.join(os.environ['WINDIR'], 'winsxs')
if not os.path.exists(winsxs_path):
return None
for root, dirs, files in os.walk(winsxs_path):
if dll_name in files and arch in root:
return os.path.join(root, dll_name)
return None
def _find_dll_in_path(dll_name):
# First, look in the Python directory, then scan PATH for
# the given dll name.
for path in [sys.prefix] + os.environ['PATH'].split(';'):
filepath = os.path.join(path, dll_name)
if os.path.exists(filepath):
return os.path.abspath(filepath)
return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name)
def build_msvcr_library(debug=False):
if os.name != 'nt':
return False
msvcr_name = msvc_runtime_library()
# Skip using a custom library for versions < MSVC 8.0
if int(msvcr_name.lstrip('msvcr')) < 80:
log.debug('Skip building msvcr library:'
' custom functionality not present')
return False
if debug:
msvcr_name += 'd'
# Skip if custom library already exists
out_name = "lib%s.a" % msvcr_name
out_file = os.path.join(sys.prefix, 'libs', out_name)
if os.path.isfile(out_file):
log.debug('Skip building msvcr library: "%s" exists' %
(out_file,))
return True
# Find the msvcr dll
msvcr_dll_name = msvcr_name + '.dll'
dll_file = find_dll(msvcr_dll_name)
if not dll_file:
log.warn('Cannot build msvcr library: "%s" not found' %
msvcr_dll_name)
return False
def_name = "lib%s.def" % msvcr_name
def_file = os.path.join(sys.prefix, 'libs', def_name)
log.info('Building msvcr library: "%s" (from %s)' \
% (out_file, dll_file))
# Generate a symbol definition file from the msvcr dll
generate_def(dll_file, def_file)
# Create a custom mingw library for the given symbol definitions
cmd = ['dlltool', '-d', def_file, '-l', out_file]
retcode = subprocess.call(cmd)
# Clean up symbol definitions
os.remove(def_file)
return (not retcode)
def build_import_library():
if os.name != 'nt':
return
arch = get_build_architecture()
if arch == 'AMD64':
return _build_import_library_amd64()
elif arch == 'Intel':
return _build_import_library_x86()
else:
raise ValueError("Unhandled arch %s" % arch)
def _build_import_library_amd64():
dll_file = find_python_dll()
out_name = "libpython%d%d.a" % tuple(sys.version_info[:2])
out_file = os.path.join(sys.prefix, 'libs', out_name)
if os.path.isfile(out_file):
log.debug('Skip building import library: "%s" exists' %
(out_file))
return
def_name = "python%d%d.def" % tuple(sys.version_info[:2])
def_file = os.path.join(sys.prefix, 'libs', def_name)
log.info('Building import library (arch=AMD64): "%s" (from %s)' %
(out_file, dll_file))
generate_def(dll_file, def_file)
cmd = ['dlltool', '-d', def_file, '-l', out_file]
subprocess.Popen(cmd)
def _build_import_library_x86():
""" Build the import libraries for Mingw32-gcc on Windows
"""
lib_name = "python%d%d.lib" % tuple(sys.version_info[:2])
lib_file = os.path.join(sys.prefix, 'libs', lib_name)
out_name = "libpython%d%d.a" % tuple(sys.version_info[:2])
out_file = os.path.join(sys.prefix, 'libs', out_name)
if not os.path.isfile(lib_file):
log.warn('Cannot build import library: "%s" not found' % (lib_file))
return
if os.path.isfile(out_file):
log.debug('Skip building import library: "%s" exists' % (out_file))
return
log.info('Building import library (ARCH=x86): "%s"' % (out_file))
from numpy.distutils import lib2def
def_name = "python%d%d.def" % tuple(sys.version_info[:2])
def_file = os.path.join(sys.prefix, 'libs', def_name)
nm_cmd = '%s %s' % (lib2def.DEFAULT_NM, lib_file)
nm_output = lib2def.getnm(nm_cmd)
dlist, flist = lib2def.parse_nm(nm_output)
lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, open(def_file, 'w'))
dll_name = "python%d%d.dll" % tuple(sys.version_info[:2])
args = (dll_name, def_file, out_file)
cmd = 'dlltool --dllname %s --def %s --output-lib %s' % args
status = os.system(cmd)
# for now, fail silently
if status:
log.warn('Failed to build import library for gcc. Linking will fail.')
return
#=====================================
# Dealing with Visual Studio MANIFESTS
#=====================================
# Functions to deal with visual studio manifests. Manifest are a mechanism to
# enforce strong DLL versioning on windows, and has nothing to do with
# distutils MANIFEST. manifests are XML files with version info, and used by
# the OS loader; they are necessary when linking against a DLL not in the
# system path; in particular, official python 2.6 binary is built against the
# MS runtime 9 (the one from VS 2008), which is not available on most windows
# systems; python 2.6 installer does install it in the Win SxS (Side by side)
# directory, but this requires the manifest for this to work. This is a big
# mess, thanks MS for a wonderful system.
# XXX: ideally, we should use exactly the same version as used by python. I
# submitted a patch to get this version, but it was only included for python
# 2.6.1 and above. So for versions below, we use a "best guess".
_MSVCRVER_TO_FULLVER = {}
if sys.platform == 'win32':
try:
import msvcrt
# I took one version in my SxS directory: no idea if it is the good
# one, and we can't retrieve it from python
_MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42"
_MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8"
# Value from msvcrt.CRT_ASSEMBLY_VERSION under Python 3.3.0
# on Windows XP:
_MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460"
if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"):
major, minor, rest = msvcrt.CRT_ASSEMBLY_VERSION.split(".", 2)
_MSVCRVER_TO_FULLVER[major + minor] = msvcrt.CRT_ASSEMBLY_VERSION
del major, minor, rest
except ImportError:
# If we are here, means python was not built with MSVC. Not sure what
# to do in that case: manifest building will fail, but it should not be
# used in that case anyway
log.warn('Cannot import msvcrt: using manifest will not be possible')
def msvc_manifest_xml(maj, min):
"""Given a major and minor version of the MSVCR, returns the
corresponding XML file."""
try:
fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)]
except KeyError:
raise ValueError("Version %d,%d of MSVCRT not supported yet" %
(maj, min))
# Don't be fooled, it looks like an XML, but it is not. In particular, it
# should not have any space before starting, and its size should be
# divisible by 4, most likely for alignement constraints when the xml is
# embedded in the binary...
# This template was copied directly from the python 2.6 binary (using
# strings.exe from mingw on python.exe).
template = """\
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC%(maj)d%(min)d.CRT" version="%(fullver)s" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
</dependentAssembly>
</dependency>
</assembly>"""
return template % {'fullver': fullver, 'maj': maj, 'min': min}
def manifest_rc(name, type='dll'):
"""Return the rc file used to generate the res file which will be embedded
as manifest for given manifest file name, of given type ('dll' or
'exe').
Parameters
----------
name : str
name of the manifest file to embed
type : str {'dll', 'exe'}
type of the binary which will embed the manifest
"""
if type == 'dll':
rctype = 2
elif type == 'exe':
rctype = 1
else:
raise ValueError("Type %s not supported" % type)
return """\
#include "winuser.h"
%d RT_MANIFEST %s""" % (rctype, name)
def check_embedded_msvcr_match_linked(msver):
"""msver is the ms runtime version used for the MANIFEST."""
# check msvcr major version are the same for linking and
# embedding
msvcv = msvc_runtime_library()
if msvcv:
assert msvcv.startswith("msvcr"), msvcv
# Dealing with something like "mscvr90" or "mscvr100", the last
# last digit is the minor release, want int("9") or int("10"):
maj = int(msvcv[5:-1])
if not maj == int(msver):
raise ValueError(
"Discrepancy between linked msvcr " \
"(%d) and the one about to be embedded " \
"(%d)" % (int(msver), maj))
def configtest_name(config):
base = os.path.basename(config._gen_temp_sourcefile("yo", [], "c"))
return os.path.splitext(base)[0]
def manifest_name(config):
# Get configest name (including suffix)
root = configtest_name(config)
exext = config.compiler.exe_extension
return root + exext + ".manifest"
def rc_name(config):
# Get configtest name (including suffix)
root = configtest_name(config)
return root + ".rc"
def generate_manifest(config):
msver = get_build_msvc_version()
if msver is not None:
if msver >= 8:
check_embedded_msvcr_match_linked(msver)
ma = int(msver)
mi = int((msver - ma) * 10)
# Write the manifest file
manxml = msvc_manifest_xml(ma, mi)
man = open(manifest_name(config), "w")
config.temp_files.append(manifest_name(config))
man.write(manxml)
man.close()
| 38.171667 | 176 | 0.590752 | from __future__ import division, absolute_import, print_function
import os
import sys
import subprocess
import re
import numpy.distutils.ccompiler
if sys.version_info[0] < 3:
from . import log
else:
from numpy.distutils import log
# --> this is done in numpy/distutils/ccompiler.py
# 3. Force windows to use g77
import distutils.cygwinccompiler
from distutils.version import StrictVersion
from numpy.distutils.ccompiler import gen_preprocess_options, gen_lib_options
from distutils.unixccompiler import UnixCCompiler
from distutils.msvccompiler import get_build_version as get_build_msvc_version
from distutils.errors import (DistutilsExecError, CompileError,
UnknownFileError)
from numpy.distutils.misc_util import (msvc_runtime_library,
get_build_architecture)
# Useful to generate table of symbols from a dll
_START = re.compile(r'\[Ordinal/Name Pointer\] Table')
_TABLE = re.compile(r'^\s+\[([\s*[0-9]*)\] ([a-zA-Z0-9_]*)')
# the same as cygwin plus some additional parameters
class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler):
compiler_type = 'mingw32'
def __init__ (self,
verbose=0,
dry_run=0,
force=0):
distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose,
dry_run, force)
# we need to support 3.2 which doesn't match the standard
if self.gcc_version is None:
import re
p = subprocess.Popen(['gcc', '-dumpversion'], shell=True,
stdout=subprocess.PIPE)
out_string = p.stdout.read()
p.stdout.close()
result = re.search('(\d+\.\d+)', out_string)
if result:
self.gcc_version = StrictVersion(result.group(1))
# but cygwin 2.91.57 in no-cygwin-mode needs it.
if self.gcc_version <= "2.91.57":
entry_point = '--entry _DllMain@12'
else:
entry_point = ''
if self.linker_dll == 'dllwrap':
# Commented out '--driver-name g++' part that fixes weird
# g++.exe: g++: No such file or directory
# error (mingw 1.0 in Enthon24 tree, gcc-3.4.5).
# If the --driver-name part is required for some environment
# then make the inclusion of this part specific to that
# environment.
self.linker = 'dllwrap' # --driver-name g++'
elif self.linker_dll == 'gcc':
self.linker = 'g++'
p = subprocess.Popen(['gcc', '--version'], shell=True,
stdout=subprocess.PIPE)
out_string = p.stdout.read()
p.stdout.close()
if 'MinGW-W64' not in str(out_string):
# **changes: eric jones 4/11/01
# 1. Check for import library on Windows. Build if it doesn't
build_import_library()
msvcr_success = build_msvcr_library()
msvcr_dbg_success = build_msvcr_library(debug=True)
if msvcr_success or msvcr_dbg_success:
# add preprocessor statement for using customized msvcr lib
self.define_macro('NPY_MINGW_USE_CUSTOM_MSVCR')
# Define the MSVC version as hint for MinGW
msvcr_version = '0x%03i0' % int(msvc_runtime_library().lstrip('msvcr'))
self.define_macro('__MSVCRT_VERSION__', msvcr_version)
# MS_WIN64 should be defined when building for amd64 on windows,
# but python headers define it only for MS compilers, which has all
# kind of bad consequences, like using Py_ModuleInit4 instead of
# Py_ModuleInit4_64, etc... So we add it here
if get_build_architecture() == 'AMD64':
if self.gcc_version < "4.0":
self.set_executables(
compiler='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0 -Wall',
compiler_so='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0'
' -Wall -Wstrict-prototypes',
linker_exe='gcc -g -mno-cygwin',
linker_so='gcc -g -mno-cygwin -shared')
else:
# gcc-4 series releases do not support -mno-cygwin option
self.set_executables(
compiler='gcc -march=x86-64 -mtune=generic -DMS_WIN64'
' -O2 -msse2 -Wall',
compiler_so='gcc -march=x86-64 -mtune=generic -DMS_WIN64'
' -O2 -msse2 -Wall -Wstrict-prototypes',
linker_exe='gcc',
linker_so='gcc -shared -Wl,-gc-sections -Wl,-s')
else:
if self.gcc_version <= "3.0.0":
self.set_executables(
compiler='gcc -mno-cygwin -O2 -w',
compiler_so='gcc -mno-cygwin -mdll -O2 -w'
' -Wstrict-prototypes',
linker_exe='g++ -mno-cygwin',
linker_so='%s -mno-cygwin -mdll -static %s' %
(self.linker, entry_point))
elif self.gcc_version < "4.0":
self.set_executables(
compiler='gcc -mno-cygwin -O2 -Wall',
compiler_so='gcc -mno-cygwin -O2 -Wall'
' -Wstrict-prototypes',
linker_exe='g++ -mno-cygwin',
linker_so='g++ -mno-cygwin -shared')
else:
# gcc-4 series releases do not support -mno-cygwin option i686
# build needs '-mincoming-stack-boundary=2' due to ABI
# incompatibility to Win32 ABI
self.set_executables(
compiler='gcc -O2 -march=core2 -mtune=generic'
' -mfpmath=sse -msse2'
' -mincoming-stack-boundary=2 -Wall',
compiler_so='gcc -O2 -march=core2 -mtune=generic'
' -mfpmath=sse -msse2'
' -mincoming-stack-boundary=2 -Wall'
' -Wstrict-prototypes',
linker_exe='g++ ',
linker_so='g++ -shared -Wl,-gc-sections -Wl,-s')
# added for python2.3 support we can't pass it through set_executables
self.compiler_cxx = ['g++']
# no additional libraries needed
#self.dll_libraries=[]
return
# __init__ ()
def link(self,
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
export_symbols = None,
debug=0,
extra_preargs=None,
extra_postargs=None,
build_temp=None,
target_lang=None):
# Include the appropiate MSVC runtime library if Python was built
# with MSVC >= 7.0 (MinGW standard is msvcrt)
runtime_library = msvc_runtime_library()
if runtime_library:
if not libraries:
libraries = []
libraries.append(runtime_library)
args = (self,
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
None, #export_symbols, we do this in our def-file
debug,
extra_preargs,
extra_postargs,
build_temp,
target_lang)
if self.gcc_version < "3.0.0":
func = distutils.cygwinccompiler.CygwinCCompiler.link
else:
func = UnixCCompiler.link
func(*args[:func.__code__.co_argcount])
return
def object_filenames (self,
source_filenames,
strip_dir=0,
output_dir=''):
if output_dir is None: output_dir = ''
obj_names = []
for src_name in source_filenames:
# use normcase to make sure '.rc' is really '.rc' and not '.RC'
(base, ext) = os.path.splitext (os.path.normcase(src_name))
# added these lines to strip off windows drive letters
# without it, .o files are placed next to .c files
# instead of the build directory
drv, base = os.path.splitdrive(base)
if drv:
base = base[1:]
if ext not in (self.src_extensions + ['.rc', '.res']):
raise UnknownFileError(
"unknown file type '%s' (from '%s')" % \
(ext, src_name))
if strip_dir:
base = os.path.basename (base)
if ext == '.res' or ext == '.rc':
# these need to be compiled to object files
obj_names.append (os.path.join (output_dir,
base + ext + self.obj_extension))
else:
obj_names.append (os.path.join (output_dir,
base + self.obj_extension))
return obj_names
# object_filenames ()
def find_python_dll():
maj, min, micro = [int(i) for i in sys.version_info[:3]]
dllname = 'python%d%d.dll' % (maj, min)
print("Looking for %s" % dllname)
# We can't do much here:
lib_dirs = []
lib_dirs.append(sys.prefix)
lib_dirs.append(os.path.join(sys.prefix, 'lib'))
try:
lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'system32'))
except KeyError:
pass
for d in lib_dirs:
dll = os.path.join(d, dllname)
if os.path.exists(dll):
return dll
raise ValueError("%s not found in %s" % (dllname, lib_dirs))
def dump_table(dll):
st = subprocess.Popen(["objdump.exe", "-p", dll], stdout=subprocess.PIPE)
return st.stdout.readlines()
def generate_def(dll, dfile):
dump = dump_table(dll)
for i in range(len(dump)):
if _START.match(dump[i].decode()):
break
else:
raise ValueError("Symbol table not found")
syms = []
for j in range(i+1, len(dump)):
m = _TABLE.match(dump[j].decode())
if m:
syms.append((int(m.group(1).strip()), m.group(2)))
else:
break
if len(syms) == 0:
log.warn('No symbols found in %s' % dll)
d = open(dfile, 'w')
d.write('LIBRARY %s\n' % os.path.basename(dll))
d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n')
d.write(';DATA PRELOAD SINGLE\n')
d.write('\nEXPORTS\n')
for s in syms:
#d.write('@%d %s\n' % (s[0], s[1]))
d.write('%s\n' % s[1])
d.close()
def find_dll(dll_name):
arch = {'AMD64' : 'amd64',
'Intel' : 'x86'}[get_build_architecture()]
def _find_dll_in_winsxs(dll_name):
# Walk through the WinSxS directory to find the dll.
winsxs_path = os.path.join(os.environ['WINDIR'], 'winsxs')
if not os.path.exists(winsxs_path):
return None
for root, dirs, files in os.walk(winsxs_path):
if dll_name in files and arch in root:
return os.path.join(root, dll_name)
return None
def _find_dll_in_path(dll_name):
# First, look in the Python directory, then scan PATH for
# the given dll name.
for path in [sys.prefix] + os.environ['PATH'].split(';'):
filepath = os.path.join(path, dll_name)
if os.path.exists(filepath):
return os.path.abspath(filepath)
return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name)
def build_msvcr_library(debug=False):
if os.name != 'nt':
return False
msvcr_name = msvc_runtime_library()
# Skip using a custom library for versions < MSVC 8.0
if int(msvcr_name.lstrip('msvcr')) < 80:
log.debug('Skip building msvcr library:'
' custom functionality not present')
return False
if debug:
msvcr_name += 'd'
# Skip if custom library already exists
out_name = "lib%s.a" % msvcr_name
out_file = os.path.join(sys.prefix, 'libs', out_name)
if os.path.isfile(out_file):
log.debug('Skip building msvcr library: "%s" exists' %
(out_file,))
return True
# Find the msvcr dll
msvcr_dll_name = msvcr_name + '.dll'
dll_file = find_dll(msvcr_dll_name)
if not dll_file:
log.warn('Cannot build msvcr library: "%s" not found' %
msvcr_dll_name)
return False
def_name = "lib%s.def" % msvcr_name
def_file = os.path.join(sys.prefix, 'libs', def_name)
log.info('Building msvcr library: "%s" (from %s)' \
% (out_file, dll_file))
# Generate a symbol definition file from the msvcr dll
generate_def(dll_file, def_file)
# Create a custom mingw library for the given symbol definitions
cmd = ['dlltool', '-d', def_file, '-l', out_file]
retcode = subprocess.call(cmd)
# Clean up symbol definitions
os.remove(def_file)
return (not retcode)
def build_import_library():
if os.name != 'nt':
return
arch = get_build_architecture()
if arch == 'AMD64':
return _build_import_library_amd64()
elif arch == 'Intel':
return _build_import_library_x86()
else:
raise ValueError("Unhandled arch %s" % arch)
def _build_import_library_amd64():
dll_file = find_python_dll()
out_name = "libpython%d%d.a" % tuple(sys.version_info[:2])
out_file = os.path.join(sys.prefix, 'libs', out_name)
if os.path.isfile(out_file):
log.debug('Skip building import library: "%s" exists' %
(out_file))
return
def_name = "python%d%d.def" % tuple(sys.version_info[:2])
def_file = os.path.join(sys.prefix, 'libs', def_name)
log.info('Building import library (arch=AMD64): "%s" (from %s)' %
(out_file, dll_file))
generate_def(dll_file, def_file)
cmd = ['dlltool', '-d', def_file, '-l', out_file]
subprocess.Popen(cmd)
def _build_import_library_x86():
lib_name = "python%d%d.lib" % tuple(sys.version_info[:2])
lib_file = os.path.join(sys.prefix, 'libs', lib_name)
out_name = "libpython%d%d.a" % tuple(sys.version_info[:2])
out_file = os.path.join(sys.prefix, 'libs', out_name)
if not os.path.isfile(lib_file):
log.warn('Cannot build import library: "%s" not found' % (lib_file))
return
if os.path.isfile(out_file):
log.debug('Skip building import library: "%s" exists' % (out_file))
return
log.info('Building import library (ARCH=x86): "%s"' % (out_file))
from numpy.distutils import lib2def
def_name = "python%d%d.def" % tuple(sys.version_info[:2])
def_file = os.path.join(sys.prefix, 'libs', def_name)
nm_cmd = '%s %s' % (lib2def.DEFAULT_NM, lib_file)
nm_output = lib2def.getnm(nm_cmd)
dlist, flist = lib2def.parse_nm(nm_output)
lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, open(def_file, 'w'))
dll_name = "python%d%d.dll" % tuple(sys.version_info[:2])
args = (dll_name, def_file, out_file)
cmd = 'dlltool --dllname %s --def %s --output-lib %s' % args
status = os.system(cmd)
# for now, fail silently
if status:
log.warn('Failed to build import library for gcc. Linking will fail.')
return
#=====================================
# Dealing with Visual Studio MANIFESTS
#=====================================
# Functions to deal with visual studio manifests. Manifest are a mechanism to
# enforce strong DLL versioning on windows, and has nothing to do with
# distutils MANIFEST. manifests are XML files with version info, and used by
# the OS loader; they are necessary when linking against a DLL not in the
# system path; in particular, official python 2.6 binary is built against the
# MS runtime 9 (the one from VS 2008), which is not available on most windows
# systems; python 2.6 installer does install it in the Win SxS (Side by side)
# directory, but this requires the manifest for this to work. This is a big
# mess, thanks MS for a wonderful system.
# XXX: ideally, we should use exactly the same version as used by python. I
# submitted a patch to get this version, but it was only included for python
# 2.6.1 and above. So for versions below, we use a "best guess".
_MSVCRVER_TO_FULLVER = {}
if sys.platform == 'win32':
try:
import msvcrt
# I took one version in my SxS directory: no idea if it is the good
# one, and we can't retrieve it from python
_MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42"
_MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8"
_MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460"
if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"):
major, minor, rest = msvcrt.CRT_ASSEMBLY_VERSION.split(".", 2)
_MSVCRVER_TO_FULLVER[major + minor] = msvcrt.CRT_ASSEMBLY_VERSION
del major, minor, rest
except ImportError:
log.warn('Cannot import msvcrt: using manifest will not be possible')
def msvc_manifest_xml(maj, min):
try:
fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)]
except KeyError:
raise ValueError("Version %d,%d of MSVCRT not supported yet" %
(maj, min))
# should not have any space before starting, and its size should be
# divisible by 4, most likely for alignement constraints when the xml is
# embedded in the binary...
# This template was copied directly from the python 2.6 binary (using
# strings.exe from mingw on python.exe).
template = """\
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC%(maj)d%(min)d.CRT" version="%(fullver)s" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
</dependentAssembly>
</dependency>
</assembly>"""
return template % {'fullver': fullver, 'maj': maj, 'min': min}
def manifest_rc(name, type='dll'):
if type == 'dll':
rctype = 2
elif type == 'exe':
rctype = 1
else:
raise ValueError("Type %s not supported" % type)
return """\
#include "winuser.h"
%d RT_MANIFEST %s""" % (rctype, name)
def check_embedded_msvcr_match_linked(msver):
# check msvcr major version are the same for linking and
# embedding
msvcv = msvc_runtime_library()
if msvcv:
assert msvcv.startswith("msvcr"), msvcv
# Dealing with something like "mscvr90" or "mscvr100", the last
# last digit is the minor release, want int("9") or int("10"):
maj = int(msvcv[5:-1])
if not maj == int(msver):
raise ValueError(
"Discrepancy between linked msvcr " \
"(%d) and the one about to be embedded " \
"(%d)" % (int(msver), maj))
def configtest_name(config):
base = os.path.basename(config._gen_temp_sourcefile("yo", [], "c"))
return os.path.splitext(base)[0]
def manifest_name(config):
# Get configest name (including suffix)
root = configtest_name(config)
exext = config.compiler.exe_extension
return root + exext + ".manifest"
def rc_name(config):
# Get configtest name (including suffix)
root = configtest_name(config)
return root + ".rc"
def generate_manifest(config):
msver = get_build_msvc_version()
if msver is not None:
if msver >= 8:
check_embedded_msvcr_match_linked(msver)
ma = int(msver)
mi = int((msver - ma) * 10)
# Write the manifest file
manxml = msvc_manifest_xml(ma, mi)
man = open(manifest_name(config), "w")
config.temp_files.append(manifest_name(config))
man.write(manxml)
man.close()
| true | true |
f72c3c1f7ed42aa55a23fb88c63f41612e677e8b | 203 | py | Python | pyBrematic/utils/__init__.py | d-Rickyy-b/Brematic-Controller | 878ace569ff7df0617a35f595cb74244c21ebb9c | [
"MIT"
] | 11 | 2018-05-02T21:31:57.000Z | 2021-11-09T11:40:47.000Z | pyBrematic/utils/__init__.py | d-Rickyy-b/Brematic-Controller | 878ace569ff7df0617a35f595cb74244c21ebb9c | [
"MIT"
] | 20 | 2018-05-01T14:32:59.000Z | 2022-02-14T21:53:58.000Z | pyBrematic/utils/__init__.py | d-Rickyy-b/Brematic-Controller | 878ace569ff7df0617a35f595cb74244c21ebb9c | [
"MIT"
] | 5 | 2018-11-08T15:35:48.000Z | 2020-12-27T18:28:44.000Z | # -*- coding: utf-8 -*-
from .encoding import DataEncoder
from .rand import Rand
from .singleton import singleton
from .storage import Storage
__all__ = ["singleton", "Storage", "DataEncoder", "Rand"]
| 22.555556 | 57 | 0.724138 |
from .encoding import DataEncoder
from .rand import Rand
from .singleton import singleton
from .storage import Storage
__all__ = ["singleton", "Storage", "DataEncoder", "Rand"]
| true | true |
f72c3cb0514457777ed5fb9a0b71f43e86fde81c | 4,523 | py | Python | caw/tests/test_e2e.py | FNNDSC/caw | a41761c4502481f6ccb60ef6e9956464c9b30eb9 | [
"MIT"
] | null | null | null | caw/tests/test_e2e.py | FNNDSC/caw | a41761c4502481f6ccb60ef6e9956464c9b30eb9 | [
"MIT"
] | 11 | 2021-04-23T21:25:29.000Z | 2022-03-14T02:40:26.000Z | caw/tests/test_e2e.py | FNNDSC/caw | a41761c4502481f6ccb60ef6e9956464c9b30eb9 | [
"MIT"
] | 1 | 2021-10-17T16:18:30.000Z | 2021-10-17T16:18:30.000Z | """
An end-to-end test which performs the following:
1. creates a ChRIS user account.
2. caw login
3. caw search
4. caw upload --pipeline ...
5. caw download
6. caw logout
"""
import os
import unittest
import random
import string
import requests
import subprocess as sp
from tempfile import NamedTemporaryFile, TemporaryDirectory
from time import sleep
from glob import iglob
def random_string(length=12) -> str:
return ''.join(random.choice(string.ascii_letters) for x in range(length))
address = 'http://localhost:8000/api/v1/'
username = 'caw_test_' + random_string(6)
password = random_string(12)
def create_account():
res = requests.post(
f'{address}users/',
headers={
'Content-Type': 'application/vnd.collection+json',
'Accept': 'application/json'
},
json={
'template': {
'data': [
{
'name': 'email',
'value': f'{username}@babyMRI.org'
},
{
'name': 'username',
'value': username
},
{
'name': 'password',
'value': password
}
]
}
}
)
res.raise_for_status()
data = res.json()
assert 'username' in data
assert data['username'] == username
def poll_feed(feed_url: str, jobs_count: int, poll_interval=10, timeout=300) -> dict:
timer = 0
headers = {
'Accept': 'application/json'
}
data = {}
while timer <= timeout:
print(f'calling get with {feed_url}')
import logging
logging.getLogger().setLevel(logging.DEBUG)
res = requests.get(feed_url, headers=headers, auth=(username, password))
res.raise_for_status()
data = res.json()
if data['finished_jobs'] == jobs_count:
return data
sleep(poll_interval)
timer += poll_interval
return data
class TestEndToEnd(unittest.TestCase):
@unittest.skipUnless('CAW_TEST_FULL' in os.environ, 'Set CAW_TEST_FULL=y to run the end-to-end test.')
def test_endtoend(self):
create_account()
sp.run(['caw', '--address', address, '--username', username, 'login', '--password-stdin'],
input=(password + '\n'), text=True, check=True)
with NamedTemporaryFile('w', suffix='.txt', delete=False) as f:
f.write("If you steal from one author it's plagiarism; if you steal from"
"\nmany it's research."
'\n -- Wilson Mizner\n')
search = sp.check_output(['caw', 'search'], text=True)
self.assertIn('Example branching pipeline', search,
msg='"Example branching pipeline" not found in `caw search`')
feed_url = sp.check_output(['caw', 'upload', '--pipeline', 'Example branching pipeline', '--', f.name],
text=True).rstrip('\n')
self.assertTrue(feed_url.startswith(address),
msg='Feed URL was not correctly printed after `caw upload`')
self.assertTrue(feed_url.endswith('/'),
msg='Feed URL was not correctly printed after `caw upload`')
feed_data = poll_feed(feed_url, jobs_count=9)
with TemporaryDirectory() as tmpdir:
sp.run(['caw', 'download', feed_data['files'], tmpdir])
# the pipeline runs pl-dircopy --prefix L where L is a letter.
# if the DAG is constructed properly, it should produce the following prefixes
prefixes = {'', 'a', 'ba', 'ca', 'dba', 'eca', 'fca', 'gca', 'hgca'}
suffix = os.path.basename(f.name)
results = [
# example:
# '/tmp/folder/caw_test_SzvEhj/feed_10/pl-dircopy_81/pl-simpledsapp_82/pl-simpledsapp_83/pl-simpledsapp_85/data/fcatmpl_hy4m5o.txt'
# --> 'fca'
os.path.basename(fname[:-len(suffix)])
for fname in iglob(os.path.join(tmpdir, '**', '*' + suffix), recursive=True)
]
self.assertEqual(len(results), 9, msg='Incorrect number of files produced by feed.')
self.assertSetEqual(prefixes, set(results),
msg='DAG not reconstructed in the correct order.')
sp.run(['caw', 'logout'])
if __name__ == '__main__':
unittest.main()
| 34.007519 | 147 | 0.554941 |
import os
import unittest
import random
import string
import requests
import subprocess as sp
from tempfile import NamedTemporaryFile, TemporaryDirectory
from time import sleep
from glob import iglob
def random_string(length=12) -> str:
return ''.join(random.choice(string.ascii_letters) for x in range(length))
address = 'http://localhost:8000/api/v1/'
username = 'caw_test_' + random_string(6)
password = random_string(12)
def create_account():
res = requests.post(
f'{address}users/',
headers={
'Content-Type': 'application/vnd.collection+json',
'Accept': 'application/json'
},
json={
'template': {
'data': [
{
'name': 'email',
'value': f'{username}@babyMRI.org'
},
{
'name': 'username',
'value': username
},
{
'name': 'password',
'value': password
}
]
}
}
)
res.raise_for_status()
data = res.json()
assert 'username' in data
assert data['username'] == username
def poll_feed(feed_url: str, jobs_count: int, poll_interval=10, timeout=300) -> dict:
timer = 0
headers = {
'Accept': 'application/json'
}
data = {}
while timer <= timeout:
print(f'calling get with {feed_url}')
import logging
logging.getLogger().setLevel(logging.DEBUG)
res = requests.get(feed_url, headers=headers, auth=(username, password))
res.raise_for_status()
data = res.json()
if data['finished_jobs'] == jobs_count:
return data
sleep(poll_interval)
timer += poll_interval
return data
class TestEndToEnd(unittest.TestCase):
@unittest.skipUnless('CAW_TEST_FULL' in os.environ, 'Set CAW_TEST_FULL=y to run the end-to-end test.')
def test_endtoend(self):
create_account()
sp.run(['caw', '--address', address, '--username', username, 'login', '--password-stdin'],
input=(password + '\n'), text=True, check=True)
with NamedTemporaryFile('w', suffix='.txt', delete=False) as f:
f.write("If you steal from one author it's plagiarism; if you steal from"
"\nmany it's research."
'\n -- Wilson Mizner\n')
search = sp.check_output(['caw', 'search'], text=True)
self.assertIn('Example branching pipeline', search,
msg='"Example branching pipeline" not found in `caw search`')
feed_url = sp.check_output(['caw', 'upload', '--pipeline', 'Example branching pipeline', '--', f.name],
text=True).rstrip('\n')
self.assertTrue(feed_url.startswith(address),
msg='Feed URL was not correctly printed after `caw upload`')
self.assertTrue(feed_url.endswith('/'),
msg='Feed URL was not correctly printed after `caw upload`')
feed_data = poll_feed(feed_url, jobs_count=9)
with TemporaryDirectory() as tmpdir:
sp.run(['caw', 'download', feed_data['files'], tmpdir])
prefixes = {'', 'a', 'ba', 'ca', 'dba', 'eca', 'fca', 'gca', 'hgca'}
suffix = os.path.basename(f.name)
results = [
os.path.basename(fname[:-len(suffix)])
for fname in iglob(os.path.join(tmpdir, '**', '*' + suffix), recursive=True)
]
self.assertEqual(len(results), 9, msg='Incorrect number of files produced by feed.')
self.assertSetEqual(prefixes, set(results),
msg='DAG not reconstructed in the correct order.')
sp.run(['caw', 'logout'])
if __name__ == '__main__':
unittest.main()
| true | true |
f72c3ce1384bcf313ac21687415c8302c74d8838 | 5,540 | py | Python | clothingBot.py | MohamedBengezi/clothingBot | da48eec8548579be70e6990b991af8d0d9aa9c77 | [
"MIT"
] | null | null | null | clothingBot.py | MohamedBengezi/clothingBot | da48eec8548579be70e6990b991af8d0d9aa9c77 | [
"MIT"
] | 3 | 2021-03-31T19:37:57.000Z | 2021-12-13T20:32:40.000Z | clothingBot.py | MohamedBengezi/clothingBot | da48eec8548579be70e6990b991af8d0d9aa9c77 | [
"MIT"
] | null | null | null | import sys
import json
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
site_000 = 'https://apolina-kids.com/collections/all'
def findItem(prodName):
elem = driver.find_element_by_xpath('//img[contains(@alt,"'+prodName+'")]')
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(elem, 5, 5)
action.click()
action.perform()
def selectSize():
try:
select = driver.find_element_by_xpath(
"//select[@id=\"product-select-4540644753485-option-0\"]")
all_options = select.find_elements_by_tag_name("option")
for option in all_options:
value = option.get_attribute("value")
if value == "5-7Y":
print("Value is: %s" % value)
option.click()
except:
print('No select found')
def addToCart():
try:
addToCart = driver.find_element_by_xpath(
"//input[@value='Add to Cart']")
except:
print('Add To Cart button not found')
try:
addToCart.send_keys(webdriver.common.keys.Keys.RETURN)
except:
try:
addToCart.click()
except:
print("Could not click 'Add to cart'")
sleep(2)
checkout = driver.find_element_by_xpath(
"//input[@value='Check Out']")
checkout.send_keys(webdriver.common.keys.Keys.RETURN)
def clickButton(id):
if (id is None):
cont = driver.find_element_by_name("button")
else:
cont = driver.find_element_by_id(id)
cont.send_keys(webdriver.common.keys.Keys.RETURN)
def shippingDetails():
with open('info.json') as f:
data = json.load(f)
email = driver.find_element_by_id("checkout_email")
email.send_keys(data['email'])
firstName = driver.find_element_by_id(
"checkout_shipping_address_first_name")
firstName.send_keys(data['firstName'])
lastName = driver.find_element_by_id("checkout_shipping_address_last_name")
lastName.send_keys(data['lastName'])
address = driver.find_element_by_id(
"checkout_shipping_address_address1")
address.send_keys(data['address'])
try:
aprtment = driver.find_element_by_id(
"checkout_shipping_address_address2")
aprtment.send_keys(data['apartment'])
except:
print('Not an apartment')
city = driver.find_element_by_id(
"checkout_shipping_address_city")
city.send_keys(data['city'])
country = driver.find_element_by_id(
"checkout_shipping_address_country")
all_options = country.find_elements_by_tag_name("option")
for option in all_options:
value = option.get_attribute("value")
if value == "United States":
option.click()
break
state = driver.find_element_by_id(
"checkout_shipping_address_province")
state_options = state.find_elements_by_tag_name("option")
for states in state_options:
value1 = states.get_attribute("value")
print("Value1 is: %s" % value1)
if value1 == data['state']:
print("Value is: %s" % value1)
states.click()
break
zipcode = driver.find_element_by_id(
"checkout_shipping_address_zip")
zipcode.send_keys(data['zipcode'])
phone = driver.find_element_by_id("checkout_shipping_address_phone")
phone.send_keys(data['phone'])
# def inputPayment():
# driver.switch_to.frame(driver.find_element_by_xpath(
# "//*[contains(@id,'card-fields-number')]"))
# wait = WebDriverWait(driver, 10)
# wait.until(EC.frame_to_be_available_and_switch_to_it(
# (By.CLASS_NAME, "card-fields-iframe")))
# cardNumber = driver.find_element_by_id("number")
# cardNumber.send_keys('4930 0000 0000 0000')
# name = WebDriverWait(driver, 20).until(EC.element_to_be_clickable(
# (By.XPATH, "//input[@id='name']")))
# driver.execute_script("arguments[0].setAttribute(arguments[1], arguments[2]);",
# name,
# "value",
# "NNAAAAMME")
# name.send_keys('NAME')
# name.send_keys(webdriver.common.keys.Keys.RETURN)
# js = "arguments[0].setAttribute('value','\"+NAME+\"')"
# expiry = driver.find_element_by_id("expiry")
# driver.execute_script("arguments[0].setAttribute(arguments[1], arguments[2]);",
# expiry,
# "value",
# "04 / 34")
# verification_value = driver.find_element_by_id("verification_value")
# driver.execute_script("arguments[0].setAttribute(arguments[1], arguments[2]);",
# verification_value,
# "value",
# "123")
# sleep(10)
# driver.switch_to.default_content()
if __name__ == '__main__':
# setting the site and driver
driver = webdriver.Firefox()
# load the site
URL = site_000
driver.get(URL)
sleep(1)
findItem('POL DRESS - FARM CHECK / HAY')
sleep(1)
selectSize()
addToCart()
sleep(3)
shippingDetails()
clickButton(None)
sleep(2.5)
clickButton(None)
sleep(3)
| 31.657143 | 85 | 0.638809 | import sys
import json
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
site_000 = 'https://apolina-kids.com/collections/all'
def findItem(prodName):
elem = driver.find_element_by_xpath('//img[contains(@alt,"'+prodName+'")]')
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(elem, 5, 5)
action.click()
action.perform()
def selectSize():
try:
select = driver.find_element_by_xpath(
"//select[@id=\"product-select-4540644753485-option-0\"]")
all_options = select.find_elements_by_tag_name("option")
for option in all_options:
value = option.get_attribute("value")
if value == "5-7Y":
print("Value is: %s" % value)
option.click()
except:
print('No select found')
def addToCart():
try:
addToCart = driver.find_element_by_xpath(
"//input[@value='Add to Cart']")
except:
print('Add To Cart button not found')
try:
addToCart.send_keys(webdriver.common.keys.Keys.RETURN)
except:
try:
addToCart.click()
except:
print("Could not click 'Add to cart'")
sleep(2)
checkout = driver.find_element_by_xpath(
"//input[@value='Check Out']")
checkout.send_keys(webdriver.common.keys.Keys.RETURN)
def clickButton(id):
if (id is None):
cont = driver.find_element_by_name("button")
else:
cont = driver.find_element_by_id(id)
cont.send_keys(webdriver.common.keys.Keys.RETURN)
def shippingDetails():
with open('info.json') as f:
data = json.load(f)
email = driver.find_element_by_id("checkout_email")
email.send_keys(data['email'])
firstName = driver.find_element_by_id(
"checkout_shipping_address_first_name")
firstName.send_keys(data['firstName'])
lastName = driver.find_element_by_id("checkout_shipping_address_last_name")
lastName.send_keys(data['lastName'])
address = driver.find_element_by_id(
"checkout_shipping_address_address1")
address.send_keys(data['address'])
try:
aprtment = driver.find_element_by_id(
"checkout_shipping_address_address2")
aprtment.send_keys(data['apartment'])
except:
print('Not an apartment')
city = driver.find_element_by_id(
"checkout_shipping_address_city")
city.send_keys(data['city'])
country = driver.find_element_by_id(
"checkout_shipping_address_country")
all_options = country.find_elements_by_tag_name("option")
for option in all_options:
value = option.get_attribute("value")
if value == "United States":
option.click()
break
state = driver.find_element_by_id(
"checkout_shipping_address_province")
state_options = state.find_elements_by_tag_name("option")
for states in state_options:
value1 = states.get_attribute("value")
print("Value1 is: %s" % value1)
if value1 == data['state']:
print("Value is: %s" % value1)
states.click()
break
zipcode = driver.find_element_by_id(
"checkout_shipping_address_zip")
zipcode.send_keys(data['zipcode'])
phone = driver.find_element_by_id("checkout_shipping_address_phone")
phone.send_keys(data['phone'])
if __name__ == '__main__':
driver = webdriver.Firefox()
URL = site_000
driver.get(URL)
sleep(1)
findItem('POL DRESS - FARM CHECK / HAY')
sleep(1)
selectSize()
addToCart()
sleep(3)
shippingDetails()
clickButton(None)
sleep(2.5)
clickButton(None)
sleep(3)
| true | true |
f72c3d058896a02a0504926742ddd9e972b29447 | 15,106 | py | Python | twilio/rest/conversations/v1/service/configuration/notification.py | timgates42/twilio-python | ef29d03a4857b62b616df4a8f4f2b7c294afbb99 | [
"MIT"
] | 2 | 2022-01-13T10:58:03.000Z | 2022-03-16T07:12:17.000Z | venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/notification.py | syt1209/PythonProjects | 0409dbd3c0b0ddf00debc38875059c828eb31dec | [
"MIT"
] | 9 | 2018-05-07T21:59:44.000Z | 2022-01-29T22:49:29.000Z | venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/notification.py | syt1209/PythonProjects | 0409dbd3c0b0ddf00debc38875059c828eb31dec | [
"MIT"
] | 4 | 2021-03-25T09:00:08.000Z | 2021-08-05T06:54:23.000Z | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class NotificationList(ListResource):
def __init__(self, version, chat_service_sid):
"""
Initialize the NotificationList
:param Version version: Version that contains the resource
:param chat_service_sid: The unique string that identifies the resource
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationList
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationList
"""
super(NotificationList, self).__init__(version)
# Path Solution
self._solution = {'chat_service_sid': chat_service_sid, }
def get(self):
"""
Constructs a NotificationContext
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
"""
return NotificationContext(self._version, chat_service_sid=self._solution['chat_service_sid'], )
def __call__(self):
"""
Constructs a NotificationContext
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
"""
return NotificationContext(self._version, chat_service_sid=self._solution['chat_service_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Conversations.V1.NotificationList>'
class NotificationPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the NotificationPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param chat_service_sid: The unique string that identifies the resource
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationPage
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationPage
"""
super(NotificationPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of NotificationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Conversations.V1.NotificationPage>'
class NotificationContext(InstanceContext):
def __init__(self, version, chat_service_sid):
"""
Initialize the NotificationContext
:param Version version: Version that contains the resource
:param chat_service_sid: The SID of the Conversation Service that the Configuration applies to.
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
"""
super(NotificationContext, self).__init__(version)
# Path Solution
self._solution = {'chat_service_sid': chat_service_sid, }
self._uri = '/Services/{chat_service_sid}/Configuration/Notifications'.format(**self._solution)
def update(self, log_enabled=values.unset, new_message_enabled=values.unset,
new_message_template=values.unset, new_message_sound=values.unset,
new_message_badge_count_enabled=values.unset,
added_to_conversation_enabled=values.unset,
added_to_conversation_template=values.unset,
added_to_conversation_sound=values.unset,
removed_from_conversation_enabled=values.unset,
removed_from_conversation_template=values.unset,
removed_from_conversation_sound=values.unset):
"""
Update the NotificationInstance
:param bool log_enabled: Weather the notification logging is enabled.
:param bool new_message_enabled: Whether to send a notification when a new message is added to a conversation.
:param unicode new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation.
:param unicode new_message_sound: The name of the sound to play when a new message is added to a conversation.
:param bool new_message_badge_count_enabled: Whether the new message badge is enabled.
:param bool added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation.
:param unicode added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation.
:param unicode added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation.
:param bool removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation.
:param unicode removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed.
:param unicode removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation.
:returns: The updated NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
data = values.of({
'LogEnabled': log_enabled,
'NewMessage.Enabled': new_message_enabled,
'NewMessage.Template': new_message_template,
'NewMessage.Sound': new_message_sound,
'NewMessage.BadgeCountEnabled': new_message_badge_count_enabled,
'AddedToConversation.Enabled': added_to_conversation_enabled,
'AddedToConversation.Template': added_to_conversation_template,
'AddedToConversation.Sound': added_to_conversation_sound,
'RemovedFromConversation.Enabled': removed_from_conversation_enabled,
'RemovedFromConversation.Template': removed_from_conversation_template,
'RemovedFromConversation.Sound': removed_from_conversation_sound,
})
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def fetch(self):
"""
Fetch the NotificationInstance
:returns: The fetched NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Conversations.V1.NotificationContext {}>'.format(context)
class NotificationInstance(InstanceResource):
def __init__(self, version, payload, chat_service_sid):
"""
Initialize the NotificationInstance
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
super(NotificationInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'chat_service_sid': payload.get('chat_service_sid'),
'new_message': payload.get('new_message'),
'added_to_conversation': payload.get('added_to_conversation'),
'removed_from_conversation': payload.get('removed_from_conversation'),
'log_enabled': payload.get('log_enabled'),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'chat_service_sid': chat_service_sid, }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: NotificationContext for this NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
"""
if self._context is None:
self._context = NotificationContext(
self._version,
chat_service_sid=self._solution['chat_service_sid'],
)
return self._context
@property
def account_sid(self):
"""
:returns: The unique ID of the Account responsible for this configuration.
:rtype: unicode
"""
return self._properties['account_sid']
@property
def chat_service_sid(self):
"""
:returns: The SID of the Conversation Service that the Configuration applies to.
:rtype: unicode
"""
return self._properties['chat_service_sid']
@property
def new_message(self):
"""
:returns: The Push Notification configuration for New Messages.
:rtype: dict
"""
return self._properties['new_message']
@property
def added_to_conversation(self):
"""
:returns: The Push Notification configuration for being added to a Conversation.
:rtype: dict
"""
return self._properties['added_to_conversation']
@property
def removed_from_conversation(self):
"""
:returns: The Push Notification configuration for being removed from a Conversation.
:rtype: dict
"""
return self._properties['removed_from_conversation']
@property
def log_enabled(self):
"""
:returns: Weather the notification logging is enabled.
:rtype: bool
"""
return self._properties['log_enabled']
@property
def url(self):
"""
:returns: An absolute URL for this configuration.
:rtype: unicode
"""
return self._properties['url']
def update(self, log_enabled=values.unset, new_message_enabled=values.unset,
new_message_template=values.unset, new_message_sound=values.unset,
new_message_badge_count_enabled=values.unset,
added_to_conversation_enabled=values.unset,
added_to_conversation_template=values.unset,
added_to_conversation_sound=values.unset,
removed_from_conversation_enabled=values.unset,
removed_from_conversation_template=values.unset,
removed_from_conversation_sound=values.unset):
"""
Update the NotificationInstance
:param bool log_enabled: Weather the notification logging is enabled.
:param bool new_message_enabled: Whether to send a notification when a new message is added to a conversation.
:param unicode new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation.
:param unicode new_message_sound: The name of the sound to play when a new message is added to a conversation.
:param bool new_message_badge_count_enabled: Whether the new message badge is enabled.
:param bool added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation.
:param unicode added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation.
:param unicode added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation.
:param bool removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation.
:param unicode removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed.
:param unicode removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation.
:returns: The updated NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
return self._proxy.update(
log_enabled=log_enabled,
new_message_enabled=new_message_enabled,
new_message_template=new_message_template,
new_message_sound=new_message_sound,
new_message_badge_count_enabled=new_message_badge_count_enabled,
added_to_conversation_enabled=added_to_conversation_enabled,
added_to_conversation_template=added_to_conversation_template,
added_to_conversation_sound=added_to_conversation_sound,
removed_from_conversation_enabled=removed_from_conversation_enabled,
removed_from_conversation_template=removed_from_conversation_template,
removed_from_conversation_sound=removed_from_conversation_sound,
)
def fetch(self):
"""
Fetch the NotificationInstance
:returns: The fetched NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
return self._proxy.fetch()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Conversations.V1.NotificationInstance {}>'.format(context)
| 42.672316 | 163 | 0.693632 |
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class NotificationList(ListResource):
def __init__(self, version, chat_service_sid):
super(NotificationList, self).__init__(version)
self._solution = {'chat_service_sid': chat_service_sid, }
def get(self):
return NotificationContext(self._version, chat_service_sid=self._solution['chat_service_sid'], )
def __call__(self):
return NotificationContext(self._version, chat_service_sid=self._solution['chat_service_sid'], )
def __repr__(self):
return '<Twilio.Conversations.V1.NotificationList>'
class NotificationPage(Page):
def __init__(self, version, response, solution):
super(NotificationPage, self).__init__(version, response)
self._solution = solution
def get_instance(self, payload):
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def __repr__(self):
return '<Twilio.Conversations.V1.NotificationPage>'
class NotificationContext(InstanceContext):
def __init__(self, version, chat_service_sid):
super(NotificationContext, self).__init__(version)
self._solution = {'chat_service_sid': chat_service_sid, }
self._uri = '/Services/{chat_service_sid}/Configuration/Notifications'.format(**self._solution)
def update(self, log_enabled=values.unset, new_message_enabled=values.unset,
new_message_template=values.unset, new_message_sound=values.unset,
new_message_badge_count_enabled=values.unset,
added_to_conversation_enabled=values.unset,
added_to_conversation_template=values.unset,
added_to_conversation_sound=values.unset,
removed_from_conversation_enabled=values.unset,
removed_from_conversation_template=values.unset,
removed_from_conversation_sound=values.unset):
data = values.of({
'LogEnabled': log_enabled,
'NewMessage.Enabled': new_message_enabled,
'NewMessage.Template': new_message_template,
'NewMessage.Sound': new_message_sound,
'NewMessage.BadgeCountEnabled': new_message_badge_count_enabled,
'AddedToConversation.Enabled': added_to_conversation_enabled,
'AddedToConversation.Template': added_to_conversation_template,
'AddedToConversation.Sound': added_to_conversation_sound,
'RemovedFromConversation.Enabled': removed_from_conversation_enabled,
'RemovedFromConversation.Template': removed_from_conversation_template,
'RemovedFromConversation.Sound': removed_from_conversation_sound,
})
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def fetch(self):
payload = self._version.fetch(method='GET', uri=self._uri, )
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def __repr__(self):
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Conversations.V1.NotificationContext {}>'.format(context)
class NotificationInstance(InstanceResource):
def __init__(self, version, payload, chat_service_sid):
super(NotificationInstance, self).__init__(version)
self._properties = {
'account_sid': payload.get('account_sid'),
'chat_service_sid': payload.get('chat_service_sid'),
'new_message': payload.get('new_message'),
'added_to_conversation': payload.get('added_to_conversation'),
'removed_from_conversation': payload.get('removed_from_conversation'),
'log_enabled': payload.get('log_enabled'),
'url': payload.get('url'),
}
self._context = None
self._solution = {'chat_service_sid': chat_service_sid, }
@property
def _proxy(self):
if self._context is None:
self._context = NotificationContext(
self._version,
chat_service_sid=self._solution['chat_service_sid'],
)
return self._context
@property
def account_sid(self):
return self._properties['account_sid']
@property
def chat_service_sid(self):
return self._properties['chat_service_sid']
@property
def new_message(self):
return self._properties['new_message']
@property
def added_to_conversation(self):
return self._properties['added_to_conversation']
@property
def removed_from_conversation(self):
return self._properties['removed_from_conversation']
@property
def log_enabled(self):
return self._properties['log_enabled']
@property
def url(self):
return self._properties['url']
def update(self, log_enabled=values.unset, new_message_enabled=values.unset,
new_message_template=values.unset, new_message_sound=values.unset,
new_message_badge_count_enabled=values.unset,
added_to_conversation_enabled=values.unset,
added_to_conversation_template=values.unset,
added_to_conversation_sound=values.unset,
removed_from_conversation_enabled=values.unset,
removed_from_conversation_template=values.unset,
removed_from_conversation_sound=values.unset):
return self._proxy.update(
log_enabled=log_enabled,
new_message_enabled=new_message_enabled,
new_message_template=new_message_template,
new_message_sound=new_message_sound,
new_message_badge_count_enabled=new_message_badge_count_enabled,
added_to_conversation_enabled=added_to_conversation_enabled,
added_to_conversation_template=added_to_conversation_template,
added_to_conversation_sound=added_to_conversation_sound,
removed_from_conversation_enabled=removed_from_conversation_enabled,
removed_from_conversation_template=removed_from_conversation_template,
removed_from_conversation_sound=removed_from_conversation_sound,
)
def fetch(self):
return self._proxy.fetch()
def __repr__(self):
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Conversations.V1.NotificationInstance {}>'.format(context)
| true | true |
f72c3d8a0d20aa867b3ae48210aa041fe0e1ebf3 | 516 | py | Python | env/Lib/site-packages/plotly/validators/violin/_points.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 11,750 | 2015-10-12T07:03:39.000Z | 2022-03-31T20:43:15.000Z | env/Lib/site-packages/plotly/validators/violin/_points.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 2,951 | 2015-10-12T00:41:25.000Z | 2022-03-31T22:19:26.000Z | env/Lib/site-packages/plotly/validators/violin/_points.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 2,623 | 2015-10-15T14:40:27.000Z | 2022-03-28T16:05:50.000Z | import _plotly_utils.basevalidators
class PointsValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="points", parent_name="violin", **kwargs):
super(PointsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
values=kwargs.pop(
"values", ["all", "outliers", "suspectedoutliers", False]
),
**kwargs
)
| 34.4 | 77 | 0.622093 | import _plotly_utils.basevalidators
class PointsValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="points", parent_name="violin", **kwargs):
super(PointsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
values=kwargs.pop(
"values", ["all", "outliers", "suspectedoutliers", False]
),
**kwargs
)
| true | true |
f72c3deb6a646c951f899749fe2ceefc65d3ed16 | 5,534 | py | Python | plotly/graph_objs/layout/scene/_domain.py | omridanan/plotly.py | a8d26670cba49ce15ce9b7639ae0f55a6088a825 | [
"MIT"
] | null | null | null | plotly/graph_objs/layout/scene/_domain.py | omridanan/plotly.py | a8d26670cba49ce15ce9b7639ae0f55a6088a825 | [
"MIT"
] | null | null | null | plotly/graph_objs/layout/scene/_domain.py | omridanan/plotly.py | a8d26670cba49ce15ce9b7639ae0f55a6088a825 | [
"MIT"
] | 1 | 2019-02-18T04:12:56.000Z | 2019-02-18T04:12:56.000Z | from plotly.basedatatypes import BaseLayoutHierarchyType
import copy
class Domain(BaseLayoutHierarchyType):
# column
# ------
@property
def column(self):
"""
If there is a layout grid, use the domain for this column in
the grid for this scene subplot .
The 'column' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self['column']
@column.setter
def column(self, val):
self['column'] = val
# row
# ---
@property
def row(self):
"""
If there is a layout grid, use the domain for this row in the
grid for this scene subplot .
The 'row' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self['row']
@row.setter
def row(self, val):
self['row'] = val
# x
# -
@property
def x(self):
"""
Sets the horizontal domain of this scene subplot (in plot
fraction).
The 'x' property is an info array that may be specified as a
list or tuple of 2 elements where:
(0) The 'x[0]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
(1) The 'x[1]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
list
"""
return self['x']
@x.setter
def x(self, val):
self['x'] = val
# y
# -
@property
def y(self):
"""
Sets the vertical domain of this scene subplot (in plot
fraction).
The 'y' property is an info array that may be specified as a
list or tuple of 2 elements where:
(0) The 'y[0]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
(1) The 'y[1]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
list
"""
return self['y']
@y.setter
def y(self, val):
self['y'] = val
# property parent name
# --------------------
@property
def _parent_path_str(self):
return 'layout.scene'
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
column
If there is a layout grid, use the domain for this
column in the grid for this scene subplot .
row
If there is a layout grid, use the domain for this row
in the grid for this scene subplot .
x
Sets the horizontal domain of this scene subplot (in
plot fraction).
y
Sets the vertical domain of this scene subplot (in plot
fraction).
"""
def __init__(
self, arg=None, column=None, row=None, x=None, y=None, **kwargs
):
"""
Construct a new Domain object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of plotly.graph_objs.layout.scene.Domain
column
If there is a layout grid, use the domain for this
column in the grid for this scene subplot .
row
If there is a layout grid, use the domain for this row
in the grid for this scene subplot .
x
Sets the horizontal domain of this scene subplot (in
plot fraction).
y
Sets the vertical domain of this scene subplot (in plot
fraction).
Returns
-------
Domain
"""
super(Domain, self).__init__('domain')
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.scene.Domain
constructor must be a dict or
an instance of plotly.graph_objs.layout.scene.Domain"""
)
# Import validators
# -----------------
from plotly.validators.layout.scene import (domain as v_domain)
# Initialize validators
# ---------------------
self._validators['column'] = v_domain.ColumnValidator()
self._validators['row'] = v_domain.RowValidator()
self._validators['x'] = v_domain.XValidator()
self._validators['y'] = v_domain.YValidator()
# Populate data dict with properties
# ----------------------------------
_v = arg.pop('column', None)
self.column = column if column is not None else _v
_v = arg.pop('row', None)
self.row = row if row is not None else _v
_v = arg.pop('x', None)
self.x = x if x is not None else _v
_v = arg.pop('y', None)
self.y = y if y is not None else _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
| 27.809045 | 71 | 0.527647 | from plotly.basedatatypes import BaseLayoutHierarchyType
import copy
class Domain(BaseLayoutHierarchyType):
@property
def column(self):
return self['column']
@column.setter
def column(self, val):
self['column'] = val
@property
def row(self):
return self['row']
@row.setter
def row(self, val):
self['row'] = val
@property
def x(self):
return self['x']
@x.setter
def x(self, val):
self['x'] = val
@property
def y(self):
return self['y']
@y.setter
def y(self, val):
self['y'] = val
@property
def _parent_path_str(self):
return 'layout.scene'
@property
def _prop_descriptions(self):
return """\
column
If there is a layout grid, use the domain for this
column in the grid for this scene subplot .
row
If there is a layout grid, use the domain for this row
in the grid for this scene subplot .
x
Sets the horizontal domain of this scene subplot (in
plot fraction).
y
Sets the vertical domain of this scene subplot (in plot
fraction).
"""
def __init__(
self, arg=None, column=None, row=None, x=None, y=None, **kwargs
):
super(Domain, self).__init__('domain')
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.scene.Domain
constructor must be a dict or
an instance of plotly.graph_objs.layout.scene.Domain"""
)
from plotly.validators.layout.scene import (domain as v_domain)
self._validators['column'] = v_domain.ColumnValidator()
self._validators['row'] = v_domain.RowValidator()
self._validators['x'] = v_domain.XValidator()
self._validators['y'] = v_domain.YValidator()
_v = arg.pop('column', None)
self.column = column if column is not None else _v
_v = arg.pop('row', None)
self.row = row if row is not None else _v
_v = arg.pop('x', None)
self.x = x if x is not None else _v
_v = arg.pop('y', None)
self.y = y if y is not None else _v
self._process_kwargs(**dict(arg, **kwargs))
| true | true |
f72c3e5bb5282a9d3bfbafdfee816454ab692053 | 64,538 | py | Python | tests/test_scottbrian_algo1/test_algo_api.py | ScottBrian/scottbrian_algo1 | 57cd8fc5674507db51b1c887d5f9a68462b0ca9d | [
"MIT"
] | null | null | null | tests/test_scottbrian_algo1/test_algo_api.py | ScottBrian/scottbrian_algo1 | 57cd8fc5674507db51b1c887d5f9a68462b0ca9d | [
"MIT"
] | null | null | null | tests/test_scottbrian_algo1/test_algo_api.py | ScottBrian/scottbrian_algo1 | 57cd8fc5674507db51b1c887d5f9a68462b0ca9d | [
"MIT"
] | null | null | null | """test_algo_api.py module."""
# from datetime import datetime, timedelta
import pytest
# import sys
# from pathlib import Path
import numpy as np
import pandas as pd # type: ignore
import string
import math
from typing import Any, List, NamedTuple
# from typing_extensions import Final
from ibapi.tag_value import TagValue # type: ignore
from ibapi.contract import ComboLeg # type: ignore
from ibapi.contract import DeltaNeutralContract
from ibapi.contract import Contract, ContractDetails
from scottbrian_algo1.algo_api import AlgoApp, AlreadyConnected, \
DisconnectLockHeld, ConnectTimeout, RequestTimeout, DisconnectDuringRequest
from scottbrian_algo1.algo_maps import get_contract_dict, get_contract_obj
from scottbrian_algo1.algo_maps import get_contract_details_obj
# from scottbrian_utils.diag_msg import diag_msg
# from scottbrian_utils.file_catalog import FileCatalog
import logging
logger = logging.getLogger(__name__)
###############################################################################
# TestAlgoAppConnect class
###############################################################################
class TestAlgoAppConnect:
"""TestAlgoAppConnect class."""
def test_mock_connect_to_ib(self,
algo_app: "AlgoApp"
) -> None:
"""Test connecting to IB.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
"""
verify_algo_app_initialized(algo_app)
# we are testing connect_to_ib and the subsequent code that gets
# control as a result, such as getting the first requestID and then
# starting a separate thread for the run loop.
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_mock_connect_to_ib_with_timeout(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test connecting to IB.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
# we are testing connect_to_ib with a simulated timeout
logger.debug("about to connect")
with pytest.raises(ConnectTimeout):
algo_app.connect_to_ib("127.0.0.1",
mock_ib.PORT_FOR_REQID_TIMEOUT,
client_id=0)
# verify that algo_app is not connected
verify_algo_app_disconnected(algo_app)
assert algo_app.request_id == 0
def test_connect_to_ib_already_connected(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test connecting to IB.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
# first, connect normally to mock_ib
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_PAPER_TRADING,
client_id=0)
# verify that algo_app is connected
verify_algo_app_connected(algo_app)
# try to connect again - should get error
with pytest.raises(AlreadyConnected):
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_PAPER_TRADING,
client_id=0)
# verify that algo_app is still connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_connect_to_ib_with_lock_held(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test connecting to IB with disconnect lock held.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
# obtain the disconnect lock
logger.debug("about to obtain disconnect lock")
algo_app.disconnect_lock.acquire()
# try to connect - should get error
with pytest.raises(DisconnectLockHeld):
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is still simply initialized
verify_algo_app_initialized(algo_app)
# def test_real_connect_to_IB(self) -> None:
# """Test connecting to IB.
#
# Args:
# algo_app: instance of AlgoApp from conftest pytest fixture
# monkeypatch: pytest fixture
#
# """
# proj_dir = Path.cwd().resolve().parents[1] # back two directories
# test_cat = \
# FileCatalog({'symbols': Path(proj_dir / 't_datasets/symbols.csv')
# })
# algo_app = AlgoApp(test_cat)
# verify_algo_app_initialized(algo_app)
#
# # we are testing connect_to_ib and the subsequent code that gets
# # control as a result, such as getting the first requestID and then
# # starting a separate thread for the run loop.
# logger.debug("about to connect")
# connect_ans = algo_app.connect_to_ib("127.0.0.1", 7496, client_id=0)
#
# # verify that algo_app is connected and alive with a valid reqId
# assert connect_ans
# assert algo_app.run_thread.is_alive()
# assert algo_app.isConnected()
# assert algo_app.request_id == 1
#
# algo_app.disconnect_from_ib()
# assert not algo_app.run_thread.is_alive()
# assert not algo_app.isConnected()
###############################################################################
# connect disconnect verification
###############################################################################
def verify_algo_app_initialized(algo_app: "AlgoApp") -> None:
"""Helper function to verify the also_app instance is initialized.
Args:
algo_app: instance of AlgoApp that is to be checked
"""
assert len(algo_app.ds_catalog) > 0
assert algo_app.request_id == 0
assert algo_app.symbols.empty
assert algo_app.stock_symbols.empty
assert algo_app.response_complete_event.is_set() is False
assert algo_app.nextValidId_event.is_set() is False
assert algo_app.__repr__() == 'AlgoApp(ds_catalog)'
# assert algo_app.run_thread is None
def verify_algo_app_connected(algo_app: "AlgoApp") -> None:
"""Helper function to verify we are connected to ib.
Args:
algo_app: instance of AlgoApp that is to be checked
"""
assert algo_app.run_thread.is_alive()
assert algo_app.isConnected()
assert algo_app.request_id == 1
def verify_algo_app_disconnected(algo_app: "AlgoApp") -> None:
"""Helper function to verify we are disconnected from ib.
Args:
algo_app: instance of AlgoApp that is to be checked
"""
assert not algo_app.run_thread.is_alive()
assert not algo_app.isConnected()
###############################################################################
###############################################################################
# matching symbols
###############################################################################
###############################################################################
class ExpCounts(NamedTuple):
"""NamedTuple for the expected counts."""
sym_non_recursive: int
sym_recursive: int
stock_sym_non_recursive: int
stock_sym_recursive: int
class SymDfs:
"""Saved sym dfs."""
def __init__(self,
mock_sym_df: Any,
sym_df: Any,
mock_stock_sym_df: Any,
stock_sym_df: Any) -> None:
"""Initialize the SymDfs.
Args:
mock_sym_df: mock sym DataFrame
sym_df: symbol DataFrame
mock_stock_sym_df: mock stock symbol DataFrame
stock_sym_df: stock symbols dataFrame
"""
self.mock_sym_df = mock_sym_df
self.sym_df = sym_df
self.mock_stock_sym_df = mock_stock_sym_df
self.stock_sym_df = stock_sym_df
class TestAlgoAppMatchingSymbols:
"""TestAlgoAppMatchingSymbols class."""
def test_request_symbols_all_combos(self,
algo_app: "AlgoApp",
mock_ib: Any) -> None:
"""Test request_symbols with all patterns.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
verify_algo_app_connected(algo_app)
algo_app.request_throttle_secs = 0.01
try:
for idx, search_pattern in enumerate(
mock_ib.search_patterns()):
exp_counts = get_exp_number(search_pattern, mock_ib)
# verify symbol table has zero entries for the symbol
logger.info("calling verify_match_symbols req_type 1 "
"sym %s num %d", search_pattern, idx)
algo_app.symbols = pd.DataFrame()
algo_app.stock_symbols = pd.DataFrame()
verify_match_symbols(algo_app,
mock_ib,
search_pattern,
exp_counts=exp_counts,
req_type=1)
logger.info("calling verify_match_symbols req_type 2 "
"sym %s num %d", search_pattern, idx)
algo_app.symbols = pd.DataFrame()
algo_app.stock_symbols = pd.DataFrame()
verify_match_symbols(algo_app,
mock_ib,
search_pattern,
exp_counts=exp_counts,
req_type=2)
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug('disconnected - test case returning')
def test_request_symbols_zero_result(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test request_symbols with pattern that finds exactly 1 symbol.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
verify_algo_app_connected(algo_app)
algo_app.request_throttle_secs = 0.01
try:
exp_counts = ExpCounts(0, 0, 0, 0)
# verify symbol table has zero entries for the symbols
for idx, search_pattern in enumerate(
mock_ib.no_find_search_patterns()):
logger.info("calling verify_match_symbols req_type 1 "
"sym %s num %d", search_pattern, idx)
verify_match_symbols(algo_app,
mock_ib,
search_pattern,
exp_counts=exp_counts,
req_type=1)
logger.info("calling verify_match_symbols req_type 2 "
"sym %s num %d", search_pattern, idx)
verify_match_symbols(algo_app,
mock_ib,
search_pattern,
exp_counts=exp_counts,
req_type=2)
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug('disconnected - test case returning')
def test_get_symbols_timeout(self,
algo_app: "AlgoApp",
mock_ib: Any) -> None:
"""Test get_symbols gets timeout.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
try:
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
mock_ib.PORT_FOR_SIMULATE_REQUEST_TIMEOUT,
client_id=0)
verify_algo_app_connected(algo_app)
with pytest.raises(RequestTimeout):
algo_app.request_symbols('A')
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug('disconnected - test case returning')
def test_get_symbols_disconnect(self,
algo_app: "AlgoApp",
mock_ib: Any) -> None:
"""Test get_symbols gets disconnected while waiting.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
try:
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
mock_ib.
PORT_FOR_SIMULATE_REQUEST_DISCONNECT,
client_id=0)
verify_algo_app_connected(algo_app)
with pytest.raises(DisconnectDuringRequest):
algo_app.request_symbols('A')
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug('disconnected - test case returning')
def test_get_symbols(self,
algo_app: "AlgoApp",
mock_ib: Any) -> None:
"""Test get_symbols with pattern that finds no symbols.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
try:
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
verify_algo_app_connected(algo_app)
algo_app.request_throttle_secs = 0.01
sym_dfs = SymDfs(pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame())
# full_stock_sym_match_descs = pd.DataFrame()
# stock_symbols_ds = pd.DataFrame()
# full_sym_match_descs = pd.DataFrame()
# symbols_ds = pd.DataFrame()
# we need to loop from A to Z
for letter in string.ascii_uppercase:
logger.debug("about to verify_get_symbols for letter %s",
letter)
# full_stock_sym_match_descs, stock_symbols_ds,\
# full_sym_match_descs, symbols_ds = \
sym_dfs = verify_get_symbols(letter,
algo_app,
mock_ib,
sym_dfs)
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug('disconnected - test case returning')
def test_get_symbols_with_connect_disconnect(self,
algo_app: "AlgoApp",
mock_ib: Any) -> None:
"""Test get_symbols with pattern that finds no symbols.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
sym_dfs = SymDfs(pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame())
# full_stock_sym_match_descs = pd.DataFrame()
# full_sym_match_descs = pd.DataFrame()
# stock_symbols_ds = pd.DataFrame()
# symbols_ds = pd.DataFrame()
# we need to loop from A to Z
for letter in string.ascii_uppercase:
try:
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
verify_algo_app_connected(algo_app)
algo_app.request_throttle_secs = 0.01
logger.debug("about to verify_get_symbols for letter %s",
letter)
# full_stock_sym_match_descs, stock_symbols_ds, \
# full_sym_match_descs, symbols_ds = \
sym_dfs = verify_get_symbols(letter,
algo_app,
mock_ib,
sym_dfs)
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
###############################################################################
# matching symbols verification
###############################################################################
def verify_match_symbols(algo_app: "AlgoApp",
mock_ib: Any,
pattern: str,
exp_counts: ExpCounts,
req_type: int = 1) -> None:
"""Verify that we find symbols correctly.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
pattern: symbols to use for searching
exp_counts: recursive and non-recursive matches expected
req_type: indicates which request to do
"""
assert req_type == 1 or req_type == 2
if req_type == 1:
logger.debug("about to request_symbols for %s", pattern)
algo_app.request_symbols(pattern)
# assert algo_app.request_id == 2
else: # req_type == 2:
logger.debug("about to get_symbols_recursive for %s", pattern)
algo_app.get_symbols_recursive(pattern)
assert algo_app.request_id >= 2
# algo_app.stock_symbols.drop_duplicates(inplace=True)
logger.debug("getting stock_sym_match_descs")
symbol_starts_with_pattern = \
mock_ib.contract_descriptions['symbol'].map(
lambda symbol: symbol.startswith(pattern))
stock_sym_match_descs = mock_ib.contract_descriptions.loc[
symbol_starts_with_pattern
& (mock_ib.contract_descriptions['secType'] == 'STK')
& (mock_ib.contract_descriptions['currency'] == 'USD')
& (if_opt_in_derivativeSecTypes(mock_ib.contract_descriptions)),
['conId', 'symbol', 'secType', 'primaryExchange', 'currency',
'derivativeSecTypes']
]
sym_match_descs = mock_ib.contract_descriptions.loc[
symbol_starts_with_pattern
& ((mock_ib.contract_descriptions['secType'] != 'STK')
| (mock_ib.contract_descriptions['currency'] != 'USD')
| if_opt_not_in_derivativeSecTypes(mock_ib.contract_descriptions)
),
['conId', 'symbol', 'secType', 'primaryExchange', 'currency',
'derivativeSecTypes']
]
logger.debug("verifying results counts")
if req_type == 1:
assert len(algo_app.stock_symbols) \
== exp_counts.stock_sym_non_recursive
assert len(algo_app.symbols) == exp_counts.sym_non_recursive
assert len(stock_sym_match_descs) == exp_counts.stock_sym_recursive
assert len(sym_match_descs) == exp_counts.sym_recursive
else:
assert len(algo_app.stock_symbols) == exp_counts.stock_sym_recursive
assert len(algo_app.symbols) == exp_counts.sym_recursive
assert len(stock_sym_match_descs) == exp_counts.stock_sym_recursive
assert len(sym_match_descs) == exp_counts.sym_recursive
logger.debug("verifying results match DataFrame")
if exp_counts.stock_sym_recursive > 0:
if req_type == 1:
stock_sym_match_descs = stock_sym_match_descs.iloc[
0:exp_counts.stock_sym_non_recursive]
stock_sym_match_descs = stock_sym_match_descs.set_index(
['conId']).sort_index()
algo_app.stock_symbols.sort_index(inplace=True)
comp_df = algo_app.stock_symbols.compare(stock_sym_match_descs)
assert comp_df.empty
if exp_counts.sym_recursive > 0:
if req_type == 1:
sym_match_descs = sym_match_descs.iloc[
0:exp_counts.sym_non_recursive]
sym_match_descs = sym_match_descs.set_index(
['conId']).sort_index()
algo_app.symbols.sort_index(inplace=True)
comp_df = algo_app.symbols.compare(sym_match_descs)
assert comp_df.empty
logger.debug("all results verified for req_type %d", req_type)
def if_opt_in_derivativeSecTypes(df: Any) -> Any:
"""Find the symbols that have options.
Args:
df: pandas DataFrame of symbols
Returns:
array of boolean values used in pandas loc function
"""
ret_array = np.full(len(df), False)
for i in range(len(df)):
if 'OPT' in df.iloc[i].derivativeSecTypes:
ret_array[i] = True
return ret_array
def if_opt_not_in_derivativeSecTypes(df: Any) -> Any:
"""Find the symbols that do not have options.
Args:
df: pandas DataFrame of symbols
Returns:
array of boolean values used in pandas loc function
"""
ret_array = np.full(len(df), True)
for i in range(len(df)):
if 'OPT' in df.iloc[i].derivativeSecTypes:
ret_array[i] = False
return ret_array
def get_exp_number(search_pattern: str, mock_ib: Any) -> ExpCounts:
"""Helper function to get number of expected symbols.
Args:
search_pattern: search arg as string of one or more chars
mock_ib: mock of ib
Returns:
number of expected matches for recursive and non-recursive requests
"""
combo_factor = (1 + 3 + 3**2 + 3**3)
if len(search_pattern) > 4:
# 5 or more chars will never match (for our mock setup)
return ExpCounts(0, 0, 0, 0)
if search_pattern[0] not in string.ascii_uppercase[0:17]:
return ExpCounts(0, 0, 0, 0) # not in A-Q, inclusive
if len(search_pattern) >= 2:
if search_pattern[1] not in string.ascii_uppercase[1:3] + '.':
return ExpCounts(0, 0, 0, 0) # not in 'BC.'
combo_factor = (1 + 3 + 3**2)
if len(search_pattern) >= 3:
if search_pattern[2] not in string.ascii_uppercase[2:5]:
return ExpCounts(0, 0, 0, 0) # not in 'CDE'
combo_factor = (1 + 3)
if len(search_pattern) == 4:
if search_pattern[3] not in string.ascii_uppercase[3:5] + '.':
return ExpCounts(0, 0, 0, 0) # not in 'DE.'
combo_factor = 1
num_stock_sym_combos = 0
num_sym_combos = 0
combo = mock_ib.get_combos(search_pattern[0])
for item in combo:
if item[0] == 'STK' and item[2] == 'USD' and 'OPT' in item[3]:
num_stock_sym_combos += 1
else:
num_sym_combos += 1
exp_stock_sym_recursive = num_stock_sym_combos * combo_factor
exp_sym_recursive = num_sym_combos * combo_factor
exp_stock_sym_non_recursive = \
math.ceil(min(16, len(combo) * combo_factor)
* (num_stock_sym_combos / len(combo)))
exp_sym_non_recursive = \
math.floor(min(16, len(combo) * combo_factor)
* (num_sym_combos / len(combo)))
return ExpCounts(exp_sym_non_recursive,
exp_sym_recursive,
exp_stock_sym_non_recursive,
exp_stock_sym_recursive
)
def verify_get_symbols(letter: str,
algo_app: "AlgoApp",
mock_ib: Any,
sym_dfs: SymDfs) -> SymDfs:
"""Verify get_symbols.
Args:
letter: the single letter we are collecting symbols for
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
sym_dfs: saved DataFrames between calls
Returns:
updated sym_dfs
"""
if letter != 'A':
# verify the symbol_status ds
symbols_status_path = \
algo_app.ds_catalog.get_path('symbols_status')
logger.info('symbols_status_path: %s', symbols_status_path)
assert symbols_status_path.exists()
symbols_status = pd.read_csv(symbols_status_path,
header=0,
index_col=0)
test_letter = symbols_status.iloc[0, 0]
assert test_letter == letter
exp_counts = get_exp_number(letter, mock_ib)
logger.debug("about to get_symbols for %s", letter)
algo_app.get_symbols()
assert algo_app.request_id >= 2
logger.debug("getting stock_sym_match_descs for %s", letter)
symbol_starts_with_pattern = \
mock_ib.contract_descriptions['symbol'].map(
lambda symbol: symbol.startswith(letter))
stock_sym_match_descs = mock_ib.contract_descriptions.loc[
symbol_starts_with_pattern
& (mock_ib.contract_descriptions['secType'] == 'STK')
& (mock_ib.contract_descriptions['currency'] == 'USD')
& (if_opt_in_derivativeSecTypes(
mock_ib.contract_descriptions)),
['conId', 'symbol', 'secType', 'primaryExchange', 'currency',
'derivativeSecTypes']
]
sym_match_descs = mock_ib.contract_descriptions.loc[
symbol_starts_with_pattern
& ((mock_ib.contract_descriptions['secType'] != 'STK')
| (mock_ib.contract_descriptions['currency'] != 'USD')
| if_opt_not_in_derivativeSecTypes(mock_ib.contract_descriptions)
),
['conId', 'symbol', 'secType', 'primaryExchange', 'currency',
'derivativeSecTypes']
]
# we expect the stock_symbols to accumulate and grow, so the
# number should now be what was there from the previous
# iteration of this loop plus what we just now added
assert len(stock_sym_match_descs) == exp_counts.stock_sym_recursive
assert len(algo_app.stock_symbols) == (
exp_counts.stock_sym_recursive + len(sym_dfs.stock_sym_df))
assert len(sym_match_descs) == exp_counts.sym_recursive
assert len(algo_app.symbols) == (
exp_counts.sym_recursive + len(sym_dfs.sym_df))
if exp_counts.stock_sym_recursive > 0:
stock_sym_match_descs = stock_sym_match_descs.set_index(
['conId']).sort_index()
sym_dfs.mock_stock_sym_df \
= sym_dfs.mock_stock_sym_df.append(stock_sym_match_descs)
sym_dfs.mock_stock_sym_df.sort_index(inplace=True)
# check the data set
stock_symbols_path = algo_app.ds_catalog.get_path('stock_symbols')
logger.info('stock_symbols_path: %s', stock_symbols_path)
sym_dfs.stock_sym_df = pd.read_csv(stock_symbols_path,
header=0,
index_col=0,
converters={
'derivativeSecTypes':
lambda x: eval(x)})
comp_df = algo_app.stock_symbols.compare(sym_dfs.stock_sym_df)
assert comp_df.empty
comp_df = algo_app.stock_symbols.compare(sym_dfs.mock_stock_sym_df)
assert comp_df.empty
if exp_counts.sym_recursive > 0:
sym_match_descs = sym_match_descs.set_index(
['conId']).sort_index()
sym_dfs.mock_sym_df = \
sym_dfs.mock_sym_df.append(sym_match_descs)
sym_dfs.mock_sym_df.sort_index(inplace=True)
# check the data set
symbols_path = \
algo_app.ds_catalog.get_path('symbols')
logger.info('symbols_path: %s', symbols_path)
sym_dfs.sym_df = pd.read_csv(symbols_path,
header=0,
index_col=0,
converters={
'derivativeSecTypes':
lambda x: eval(x)})
comp_df = algo_app.symbols.compare(sym_dfs.sym_df)
assert comp_df.empty
comp_df = algo_app.symbols.compare(sym_dfs.mock_sym_df)
assert comp_df.empty
return sym_dfs
###############################################################################
###############################################################################
# error path
###############################################################################
###############################################################################
class TestErrorPath:
"""Class to test error path."""
def test_error_path_by_request_when_not_connected(self,
algo_app: "AlgoApp",
capsys: Any) -> None:
"""Test the error callback by any request while not connected.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
capsys: pytest fixture to capture print output
"""
verify_algo_app_initialized(algo_app)
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug("about to request time")
algo_app.reqCurrentTime()
captured = capsys.readouterr().out
assert captured == 'Error: -1 504 Not connected' + '\n'
###############################################################################
###############################################################################
# contract details
###############################################################################
###############################################################################
class TestAlgoAppContractDetails:
"""TestAlgoAppContractDetails class."""
def test_get_contract_details_0_entries(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test contract details for non-existent conId.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
contract = Contract() # create an empty contract with conId of 0
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [])
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_get_contract_details_1_entry(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test contract details for 1 entry.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
contract = Contract() # create an empty contract with conId of 0
contract.conId = 7001
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001])
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_get_contract_details_2_entries(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test contract details for 2 entries.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
contract = Contract() # create an empty contract with conId of 0
contract.conId = 7001
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001])
contract.conId = 7002
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001, 7002])
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_get_contract_details_duplicates(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test contract details for 3 entries plus a duplicate.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
contract = Contract() # create an empty contract with conId of 0
contract.conId = 7001
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001])
contract.conId = 7002
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001, 7002])
contract.conId = 7001 # try to add 7001 again
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001, 7002])
contract.conId = 7003
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib,
[7001, 7002, 7003])
contract.conId = 7002 # another duplicate
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib,
[7001, 7002, 7003])
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_get_contract_details_many_entries(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test contract details for many entries.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
try:
conId_list = []
for conId in range(7001, 7033):
contract = Contract() # create an empty contract
contract.conId = conId
conId_list.append(conId)
algo_app.get_contract_details(contract)
verify_contract_details(contract,
algo_app,
mock_ib,
conId_list)
finally:
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
###############################################################################
# contract details verification
###############################################################################
def verify_contract_details(contract: "Contract",
algo_app: "AlgoApp",
mock_ib: Any,
conId_list: List[int]) -> None:
"""Verify contract details.
Args:
contract: the contract used to get details
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
conId_list: list of con ids
"""
assert len(algo_app.contract_details) == len(conId_list)
if len(conId_list) > 0:
# first, save the algo_app contracts and contract_details
contracts_ds = algo_app.contracts
contract_details_ds = algo_app.contract_details
# next, reload algo_app contracts and contract_details from csv
# so we can test that they were saved and restored
# correctly (i.e., we will compare them against
# what we just loaded)
contracts_path = algo_app.ds_catalog.get_path('contracts')
logger.info('contracts_path: %s', contracts_path)
algo_app.contracts = algo_app.load_contracts(contracts_path)
algo_app.load_contract_details()
# print('contract_details_ds:\n', contract_details_ds)
# print('contract_details_ds.__dict__:\n',
# contract_details_ds.__dict__)
for conId in conId_list:
# match_desc = mock_ib.contract_descriptions.loc[
# mock_ib.contract_descriptions['conId'] == conId]
# match_desc = match_desc.iloc[0]
contract1 = get_contract_obj(
algo_app.contracts.loc[conId].to_dict())
contract2 = get_contract_obj(contracts_ds.loc[conId].to_dict())
compare_contracts(contract1,
contract2)
contract3 = get_contract_from_mock_desc(conId, mock_ib)
compare_contracts(contract1,
contract3)
contract_details1 = get_contract_details_obj(
algo_app.contract_details.loc[conId].to_dict())
contract_details2 = get_contract_details_obj(
contract_details_ds.loc[conId].to_dict())
compare_contract_details(contract_details1,
contract_details2)
contract_details3 = \
get_contract_details_from_mock_desc(conId, mock_ib)
compare_contract_details(contract_details1,
contract_details3)
###############################################################################
###############################################################################
# TestExtraContractFields
###############################################################################
###############################################################################
class TestExtraContractFields:
"""TestExtraContractFields class."""
###########################################################################
# test_contract_combo_legs
###########################################################################
def test_contract_extra_fields(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test combo legs in contract.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
num_contracts = 50
contract_list = []
contract_df = pd.DataFrame()
# get the path for saving/loading the combo legs contract df
extra_contract_path = \
algo_app.ds_catalog.get_path('extra_contract')
logger.info('extra_contract_path: %s', extra_contract_path)
for i in range(num_contracts):
conId = 7001 + i
contract = get_contract_from_mock_desc(conId,
mock_ib,
include_extra_details=True)
# add combo legs
combo_leg_list = build_combo_legs(i, mock_ib)
if combo_leg_list:
contract.comboLegs = combo_leg_list
elif i % 2 == 1: # empty list
# empty list for odd, None for even
contract.comboLegs = []
contract_list.append(contract)
contract_dict = get_contract_dict(contract)
contract_df = \
contract_df.append(pd.DataFrame(contract_dict,
index=[contract.conId]))
# Save dataframe to csv
contract_df.to_csv(extra_contract_path)
# read dataframe from csv
contract_df2 = algo_app.load_contracts(extra_contract_path)
for i in range(num_contracts):
contract1 = contract_list[i]
contract_dict2 = contract_df2.iloc[i].to_dict()
contract2 = get_contract_obj(contract_dict2)
compare_contracts(contract1, contract2)
###############################################################################
# build_combo_legs
###############################################################################
def build_combo_legs(idx: int,
mock_ib: Any) -> List[ComboLeg]:
"""Build the combo leg list for a contract.
Args:
idx: the index of the entry being built
mock_ib: pytest fixture of contract_descriptions
Returns:
list with zero or more ComboLeg items
"""
num_combo_legs = idx % 4 # vary the number built from 0 to 3
combo_leg_list = []
for j in range(num_combo_legs):
combo_leg = ComboLeg()
combo_leg.conId = \
mock_ib.combo_legs.cl_conId.iloc[idx + j]
combo_leg.ratio = \
mock_ib.combo_legs.cl_ratio.iloc[idx + j]
combo_leg.action = \
mock_ib.combo_legs.cl_action.iloc[idx + j]
combo_leg.exchange = \
mock_ib.combo_legs.cl_exchange.iloc[idx + j]
combo_leg.openClose = \
mock_ib.combo_legs.cl_openClose.iloc[idx + j]
combo_leg.shortSaleSlot = \
mock_ib.combo_legs.cl_shortSaleSlot.iloc[idx + j]
combo_leg.designatedLocation = \
mock_ib.combo_legs.cl_designatedLocation.iloc[idx + j]
combo_leg.exemptCode = \
mock_ib.combo_legs.cl_exemptCode.iloc[idx + j]
combo_leg_list.append(combo_leg)
return combo_leg_list
###############################################################################
# get_contract_from_mock_desc
###############################################################################
def get_contract_from_mock_desc(conId: int,
mock_ib: Any,
include_extra_details: bool = False
) -> Contract:
"""Build and return a contract from the mock description.
Args:
conId: index of mock_desc and mock_dnc to use
mock_ib: contains contract data frames
include_extra_details: include more details beyond what is
returned for reqContractDetails
Returns:
Contract with fields from input mock_desc and mock_dnc
"""
ret_con = Contract()
ret_con.conId = mock_ib.contract_descriptions.at[conId, 'conId'] # cd
ret_con.symbol = mock_ib.contract_descriptions.at[conId, 'symbol'] # cd
ret_con.secType = mock_ib.contract_descriptions.at[conId, 'secType'] # cd
if mock_ib.contract_descriptions.at[conId, 'lastTradeDateOrContractMonth']:
split_date = \
mock_ib.contract_descriptions.at[
conId, 'lastTradeDateOrContractMonth'].split()
if len(split_date) > 0: # very well better be!
ret_con.lastTradeDateOrContractMonth = split_date[0]
ret_con.strike = mock_ib.contract_descriptions.at[conId, 'strike'] # cd
ret_con.right = mock_ib.contract_descriptions.at[conId, 'right'] # cd
ret_con.multiplier = \
mock_ib.contract_descriptions.at[conId, 'multiplier'] # cd
ret_con.exchange = \
mock_ib.contract_descriptions.at[conId, 'exchange'] # cd
ret_con.primaryExchange = \
mock_ib.contract_descriptions.at[conId, 'primaryExchange'] # cd
ret_con.currency = \
mock_ib.contract_descriptions.at[conId, 'currency'] # cd
ret_con.localSymbol = \
mock_ib.contract_descriptions.at[conId, 'localSymbol'] # cd
ret_con.tradingClass = \
mock_ib.contract_descriptions.at[conId, 'tradingClass'] # cd
###########################################################################
# following fields are not included with reqContractDetails
###########################################################################
if include_extra_details:
ret_con.includeExpired = \
mock_ib.contract_descriptions.at[conId, 'includeExpired']
ret_con.secIdType = mock_ib.contract_descriptions.at[conId,
'secIdType']
ret_con.secId = mock_ib.contract_descriptions.at[conId, 'secId']
# combos
ret_con.comboLegsDescrip = \
mock_ib.contract_descriptions.at[conId, 'comboLegsDescrip']
# ret_con.comboLegs = mock_ib.contract_descriptions.comboLegs
# build a delta_neutral_contract every third time
if (conId % 3) == 0:
delta_neutral_contract = DeltaNeutralContract()
# item() is used to convert numpy.int64 to python int
delta_neutral_contract.conId = \
mock_ib.delta_neutral_contract.at[conId, 'conId']
delta_neutral_contract.delta = \
mock_ib.delta_neutral_contract.at[conId, 'delta']
delta_neutral_contract.price = \
mock_ib.delta_neutral_contract.at[conId, 'price']
ret_con.deltaNeutralContract = delta_neutral_contract
return ret_con
###############################################################################
# get_contract_details_from_mock_desc
###############################################################################
def get_contract_details_from_mock_desc(conId: int,
mock_ib: Any
) -> ContractDetails:
"""Build and return a contract_details from the mock description.
Args:
conId: index of entry to use
mock_ib: DataFrame with values for contract_details
Returns:
ContractDetails with fields from input mock_desc
"""
ret_con = ContractDetails()
ret_con.contract = get_contract_from_mock_desc(conId, mock_ib)
ret_con.marketName = \
mock_ib.contract_descriptions.at[conId, 'marketName'] # cd
ret_con.minTick = mock_ib.contract_descriptions.at[conId, 'minTick'] # cd
ret_con.orderTypes = \
mock_ib.contract_descriptions.at[conId, 'orderTypes'] # cd
ret_con.validExchanges = \
mock_ib.contract_descriptions.at[conId, 'validExchanges'] # cd
ret_con.priceMagnifier = \
mock_ib.contract_descriptions.at[conId, 'priceMagnifier'] # cd
ret_con.underConId = \
mock_ib.contract_descriptions.at[conId, 'underConId'] # cd
ret_con.longName = mock_ib.contract_descriptions.at[conId,
'longName'] # cd
ret_con.contractMonth = \
mock_ib.contract_descriptions.at[conId, 'contractMonth'] # cd
ret_con.industry = mock_ib.contract_descriptions.at[conId,
'industry'] # cd
ret_con.category = mock_ib.contract_descriptions.at[conId,
'category'] # cd
ret_con.subcategory = \
mock_ib.contract_descriptions.at[conId, 'subcategory'] # cd
ret_con.timeZoneId = \
mock_ib.contract_descriptions.at[conId, 'timeZoneId'] # cd
ret_con.tradingHours = \
mock_ib.contract_descriptions.at[conId, 'tradingHours'] # cd
ret_con.liquidHours = \
mock_ib.contract_descriptions.at[conId, 'liquidHours'] # cd
ret_con.evRule = mock_ib.contract_descriptions.at[conId, 'evRule'] # cd
ret_con.evMultiplier = \
mock_ib.contract_descriptions.at[conId, 'evMultiplier'] # cd
ret_con.mdSizeMultiplier = \
mock_ib.contract_descriptions.at[conId, 'mdSizeMultiplier'] # cd
ret_con.aggGroup = mock_ib.contract_descriptions.at[conId,
'aggGroup'] # cd
ret_con.underSymbol = \
mock_ib.contract_descriptions.at[conId, 'underSymbol'] # cd
ret_con.underSecType = \
mock_ib.contract_descriptions.at[conId, 'underSecType'] # cd
ret_con.marketRuleIds = \
mock_ib.contract_descriptions.at[conId, 'marketRuleIds'] # cd
secIdList = mock_ib.contract_descriptions.at[conId, 'secIdList']
new_secIdList = []
for j in range(0,
2 * mock_ib.contract_descriptions.at[conId,
'secIdListCount'],
2):
tag = secIdList[j]
value = secIdList[j+1]
tag_value = TagValue(tag, value)
new_secIdList.append(tag_value)
ret_con.secIdList = new_secIdList # cd
ret_con.realExpirationDate = \
mock_ib.contract_descriptions.at[conId, 'realExpirationDate'] # cd
# last trade time come from lastTradeDate as 'date time' (i.e., 2 items)
if mock_ib.contract_descriptions.at[conId, 'lastTradeDateOrContractMonth']:
split_date = \
mock_ib.contract_descriptions.at[
conId, 'lastTradeDateOrContractMonth'].split()
if len(split_date) > 1:
ret_con.lastTradeTime = split_date[1]
ret_con.stockType = mock_ib.contract_descriptions.at[conId,
'stockType'] # cd
return ret_con
###############################################################################
# compare_tag_value
###############################################################################
def compare_tag_value(tag_value1: TagValue,
tag_value2: TagValue
) -> None:
"""Compare two tag_value objects for equality.
Args:
tag_value1: tag_value 1
tag_value2: tag_value 2
"""
assert tag_value1.tag == tag_value2.tag
assert isinstance(tag_value1.tag, str)
assert isinstance(tag_value2.tag, str)
assert tag_value1.value == tag_value2.value
assert isinstance(tag_value1.value, str)
assert isinstance(tag_value2.value, str)
###############################################################################
# compare_combo_legs
###############################################################################
def compare_combo_legs(cl1: ComboLeg,
cl2: ComboLeg
) -> None:
"""Compare two combo leg objects for equality.
Args:
cl1: combo leg 1
cl2: combo leg 2
"""
assert cl1.conId == cl2.conId
assert cl1.ratio == cl2.ratio
assert cl1.action == cl2.action
assert cl1.exchange == cl2.exchange
assert cl1.openClose == cl2.openClose
assert cl1.shortSaleSlot == cl2.shortSaleSlot
assert cl1.designatedLocation == cl2.designatedLocation
assert cl1.exemptCode == cl2.exemptCode
verify_combo_leg_types(cl1)
verify_combo_leg_types(cl1)
###############################################################################
# verify_combo_leg_types
###############################################################################
def verify_combo_leg_types(combo_leg: ComboLeg) -> None:
"""Verify that combo_leg fields are correct type.
Args:
combo_leg: combo_leg to verify
"""
assert isinstance(combo_leg.conId, (int, np.int64))
assert isinstance(combo_leg.ratio, (int, np.int64))
assert isinstance(combo_leg.action, str)
assert isinstance(combo_leg.exchange, str)
assert isinstance(combo_leg.openClose, (int, np.int64))
assert isinstance(combo_leg.shortSaleSlot, (int, np.int64))
assert isinstance(combo_leg.designatedLocation, str)
assert isinstance(combo_leg.exemptCode, (int, np.int64))
###############################################################################
# compare_delta_neutral_contracts
###############################################################################
def compare_delta_neutral_contracts(con1: DeltaNeutralContract,
con2: DeltaNeutralContract
) -> None:
"""Compare two delta neutral contracts for equality.
Args:
con1: contract 1
con2: contract 2
"""
assert con1.conId == con2.conId
assert isinstance(con1.conId, (int, np.int64))
assert isinstance(con2.conId, int)
assert con1.delta == con2.delta
assert isinstance(con1.delta, float)
assert isinstance(con2.delta, float)
assert con1.price == con2.price
assert isinstance(con1.price, float)
assert isinstance(con2.price, float)
###############################################################################
# compare_contracts
###############################################################################
def compare_contracts(con1: Contract, con2: Contract) -> None:
"""Compare two contracts for equality.
Args:
con1: contract 1
con2: contract 2
"""
assert con1.conId == con2.conId
assert con1.symbol == con2.symbol
assert con1.secType == con2.secType
assert (con1.lastTradeDateOrContractMonth
== con2.lastTradeDateOrContractMonth)
assert con1.strike == con2.strike
assert con1.right == con2.right
assert con1.multiplier == con2.multiplier
assert con1.exchange == con2.exchange
assert con1.primaryExchange == con2.primaryExchange
assert con1.currency == con2.currency
assert con1.localSymbol == con2.localSymbol
assert con1.tradingClass == con2.tradingClass
assert con1.includeExpired == con2.includeExpired
assert con1.secIdType == con2.secIdType
assert con1.secId == con2.secId
# combos
assert con1.comboLegsDescrip == con2.comboLegsDescrip
if con1.comboLegs and con2.comboLegs:
assert len(con1.comboLegs) == len(con2.comboLegs)
for i in range(len(con1.comboLegs)):
compare_combo_legs(con1.comboLegs[i],
con2.comboLegs[i])
else: # check whether one contract has it and the other does not
assert not (con1.comboLegs or con2.comboLegs)
if con1.deltaNeutralContract and con2.deltaNeutralContract:
compare_delta_neutral_contracts(con1.deltaNeutralContract,
con2.deltaNeutralContract)
else: # check whether one contract has it and one does not
assert not (con1.deltaNeutralContract or con2.deltaNeutralContract)
verify_contract_types(con1)
verify_contract_types(con2)
###############################################################################
# verify_contract_types
###############################################################################
def verify_contract_types(contract: Contract) -> None:
"""Verify that contract fields are correct type.
Args:
contract: contract to verify
"""
assert isinstance(contract.conId, (int, np.int64))
assert isinstance(contract.symbol, str)
assert isinstance(contract.secType, str)
assert isinstance(contract.lastTradeDateOrContractMonth, str)
assert isinstance(contract.strike, float)
assert isinstance(contract.right, str)
assert isinstance(contract.multiplier, str)
assert isinstance(contract.exchange, str)
assert isinstance(contract.primaryExchange, str)
assert isinstance(contract.currency, str)
assert isinstance(contract.localSymbol, str)
assert isinstance(contract.tradingClass, str)
assert isinstance(contract.includeExpired, (bool, np.bool_))
assert isinstance(contract.secIdType, str)
assert isinstance(contract.secId, str)
# combos
assert isinstance(contract.comboLegsDescrip, str)
assert isinstance(contract.comboLegs, (list, type(None)))
if contract.comboLegs:
for combo_leg in contract.comboLegs:
assert isinstance(combo_leg, ComboLeg)
assert isinstance(contract.deltaNeutralContract,
(DeltaNeutralContract, type(None)))
###############################################################################
# compare_contract_details
###############################################################################
def compare_contract_details(con1: ContractDetails,
con2: ContractDetails
) -> None:
"""Compare two contract_details for equality.
Args:
con1: contract_details 1
con2: contract_details 2
"""
if con1.contract and con2.contract:
compare_contracts(con1.contract, con2.contract)
else: # check whether one contract_details has it, one does not
assert not (con1.contract or con2.contract)
assert con1.marketName == con2.marketName
assert con1.minTick == con2.minTick
assert con1.orderTypes == con2.orderTypes
assert con1.validExchanges == con2.validExchanges
assert con1.priceMagnifier == con2.priceMagnifier
assert con1.underConId == con2.underConId
assert con1.longName == con2.longName
assert con1.contractMonth == con2.contractMonth
assert con1.industry == con2.industry
assert con1.category == con2.category
assert con1.subcategory == con2.subcategory
assert con1.timeZoneId == con2.timeZoneId
assert con1.tradingHours == con2.tradingHours
assert con1.liquidHours == con2.liquidHours
assert con1.evRule == con2.evRule
assert con1.evMultiplier == con2.evMultiplier
assert con1.mdSizeMultiplier == con2.mdSizeMultiplier
assert con1.aggGroup == con2.aggGroup
assert con1.underSymbol == con2.underSymbol
assert con1.underSecType == con2.underSecType
assert con1.marketRuleIds == con2.marketRuleIds
if con1.secIdList and con2.secIdList:
assert len(con1.secIdList) == len(con2.secIdList)
for i in range(len(con1.secIdList)):
compare_tag_value(con1.secIdList[i], con2.secIdList[i])
else: # check whether one contract_details has it, one does not
assert not (con1.secIdList or con2.secIdList)
assert con1.realExpirationDate == con2.realExpirationDate
assert con1.lastTradeTime == con2.lastTradeTime
assert con1.stockType == con2.stockType
# BOND values
assert con1.cusip == con2.cusip
assert con1.ratings == con2.ratings
assert con1.descAppend == con2.descAppend
assert con1.bondType == con2.bondType
assert con1.couponType == con2.couponType
assert con1.callable == con2.callable
assert con1.putable == con2.putable
assert con1.coupon == con2.coupon
assert con1.convertible == con2.convertible
assert con1.maturity == con2.maturity
assert con1.issueDate == con2.issueDate
assert con1.nextOptionDate == con2.nextOptionDate
assert con1.nextOptionType == con2.nextOptionType
assert con1.nextOptionPartial == con2.nextOptionPartial
assert con1.notes == con2.notes
###############################################################################
# fundamental data
###############################################################################
# class TestAlgoAppFundamentalData:
# """TestAlgoAppContractDetails class."""
#
# def test_get_contract_details_0_entries(self,
# algo_app: "AlgoApp",
# mock_ib: Any
# ) -> None:
# """Test contract details for non-existent conId.
#
# Args:
# algo_app: pytest fixture instance of AlgoApp (see conftest.py)
# mock_ib: pytest fixture of contract_descriptions
#
# """
# verify_algo_app_initialized(algo_app)
#
# logger.debug("about to connect")
# algo_app.connect_to_ib("127.0.0.1",
# algo_app.PORT_FOR_LIVE_TRADING,
# client_id=0)
#
# # verify that algo_app is connected and alive with a valid reqId
# verify_algo_app_connected(algo_app)
#
# contract = Contract() # create an empty contract with conId of 0
# algo_app.get_contract_details(contract)
#
# verify_contract_details(contract, algo_app, mock_ib, [0])
#
# algo_app.disconnect_from_ib()
# verify_algo_app_disconnected(algo_app)
| 37.133487 | 79 | 0.562754 |
import pytest
import numpy as np
import pandas as pd
import string
import math
from typing import Any, List, NamedTuple
from ibapi.tag_value import TagValue
from ibapi.contract import ComboLeg
from ibapi.contract import DeltaNeutralContract
from ibapi.contract import Contract, ContractDetails
from scottbrian_algo1.algo_api import AlgoApp, AlreadyConnected, \
DisconnectLockHeld, ConnectTimeout, RequestTimeout, DisconnectDuringRequest
from scottbrian_algo1.algo_maps import get_contract_dict, get_contract_obj
from scottbrian_algo1.algo_maps import get_contract_details_obj
import logging
logger = logging.getLogger(__name__)
| true | true |
f72c3eaefc009d0112c0c6fa0eb8a060a2d74f83 | 13,353 | py | Python | cryptoapis/model/inline_response40084.py | Crypto-APIs/Crypto_APIs_2.0_SDK_Python | c59ebd914850622b2c6500c4c30af31fb9cecf0e | [
"MIT"
] | 5 | 2021-05-17T04:45:03.000Z | 2022-03-23T12:51:46.000Z | cryptoapis/model/inline_response40084.py | Crypto-APIs/Crypto_APIs_2.0_SDK_Python | c59ebd914850622b2c6500c4c30af31fb9cecf0e | [
"MIT"
] | null | null | null | cryptoapis/model/inline_response40084.py | Crypto-APIs/Crypto_APIs_2.0_SDK_Python | c59ebd914850622b2c6500c4c30af31fb9cecf0e | [
"MIT"
] | 2 | 2021-06-02T07:32:26.000Z | 2022-02-12T02:36:23.000Z | """
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of their blockchain applications. Crypto APIs 2.0 provides unified endpoints and data, raw data, automatic tokens and coins forwardings, callback functionalities, and much more. # noqa: E501
The version of the OpenAPI document: 2.0.0
Contact: developers@cryptoapis.io
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from cryptoapis.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
OpenApiModel
)
from cryptoapis.exceptions import ApiAttributeError
def lazy_import():
from cryptoapis.model.get_eip1559_fee_recommendations_e400 import GetEIP1559FeeRecommendationsE400
globals()['GetEIP1559FeeRecommendationsE400'] = GetEIP1559FeeRecommendationsE400
class InlineResponse40084(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
"""
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
'api_version': (str,), # noqa: E501
'request_id': (str,), # noqa: E501
'error': (GetEIP1559FeeRecommendationsE400,), # noqa: E501
'context': (str,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'api_version': 'apiVersion', # noqa: E501
'request_id': 'requestId', # noqa: E501
'error': 'error', # noqa: E501
'context': 'context', # noqa: E501
}
read_only_vars = {
}
_composed_schemas = {}
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, api_version, request_id, error, *args, **kwargs): # noqa: E501
"""InlineResponse40084 - a model defined in OpenAPI
Args:
api_version (str): Specifies the version of the API that incorporates this endpoint.
request_id (str): Defines the ID of the request. The `requestId` is generated by Crypto APIs and it's unique for every request.
error (GetEIP1559FeeRecommendationsE400):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
context (str): In batch situations the user can use the context to correlate responses with requests. This property is present regardless of whether the response was successful or returned as an error. `context` is specified by the user.. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.api_version = api_version
self.request_id = request_id
self.error = error
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
return self
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, api_version, request_id, error, *args, **kwargs): # noqa: E501
"""InlineResponse40084 - a model defined in OpenAPI
Args:
api_version (str): Specifies the version of the API that incorporates this endpoint.
request_id (str): Defines the ID of the request. The `requestId` is generated by Crypto APIs and it's unique for every request.
error (GetEIP1559FeeRecommendationsE400):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
context (str): In batch situations the user can use the context to correlate responses with requests. This property is present regardless of whether the response was successful or returned as an error. `context` is specified by the user.. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.api_version = api_version
self.request_id = request_id
self.error = error
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
if var_name in self.read_only_vars:
raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate "
f"class with read only attributes.")
| 46.852632 | 484 | 0.59642 |
import re
import sys
from cryptoapis.model_utils import (
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
OpenApiModel
)
from cryptoapis.exceptions import ApiAttributeError
def lazy_import():
from cryptoapis.model.get_eip1559_fee_recommendations_e400 import GetEIP1559FeeRecommendationsE400
globals()['GetEIP1559FeeRecommendationsE400'] = GetEIP1559FeeRecommendationsE400
class InlineResponse40084(ModelNormal):
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,)
_nullable = False
@cached_property
def openapi_types():
lazy_import()
return {
'api_version': (str,),
'request_id': (str,),
'error': (GetEIP1559FeeRecommendationsE400,),
'context': (str,),
}
@cached_property
def discriminator():
return None
attribute_map = {
'api_version': 'apiVersion',
'request_id': 'requestId',
'error': 'error',
'context': 'context',
}
read_only_vars = {
}
_composed_schemas = {}
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, api_version, request_id, error, *args, **kwargs):
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.api_version = api_version
self.request_id = request_id
self.error = error
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
continue
setattr(self, var_name, var_value)
return self
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, api_version, request_id, error, *args, **kwargs):
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.api_version = api_version
self.request_id = request_id
self.error = error
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
continue
setattr(self, var_name, var_value)
if var_name in self.read_only_vars:
raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate "
f"class with read only attributes.")
| true | true |
f72c3f4ba1a384299dbf753da7d0c4ce5d5a213d | 117 | py | Python | App/pogress.py | MarioTiara/MarioTiara-RD-Detection-Ensemble-CNN | 95101b942a7e51078bfe643021e745e51e82516f | [
"MIT"
] | null | null | null | App/pogress.py | MarioTiara/MarioTiara-RD-Detection-Ensemble-CNN | 95101b942a7e51078bfe643021e745e51e82516f | [
"MIT"
] | null | null | null | App/pogress.py | MarioTiara/MarioTiara-RD-Detection-Ensemble-CNN | 95101b942a7e51078bfe643021e745e51e82516f | [
"MIT"
] | null | null | null | from tqdm import tqdm,trange
from time import sleep
for i in trange(20):
sleep(0.1)
pass
raise SystemExit
| 11.7 | 28 | 0.709402 | from tqdm import tqdm,trange
from time import sleep
for i in trange(20):
sleep(0.1)
pass
raise SystemExit
| true | true |
f72c409dd9d8c1ef88d4e1e5c1f5d52fa3e3b565 | 546 | py | Python | manage.py | C-PRONCE/django-project | 573402850462a73bd8750118f74e2b36aa650ded | [
"MIT"
] | null | null | null | manage.py | C-PRONCE/django-project | 573402850462a73bd8750118f74e2b36aa650ded | [
"MIT"
] | null | null | null | manage.py | C-PRONCE/django-project | 573402850462a73bd8750118f74e2b36aa650ded | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "second_project.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)
| 34.125 | 78 | 0.690476 |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "second_project.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)
| true | true |
f72c41aed18c0d9acc5d31e93cff1a2cecca0807 | 2,225 | py | Python | test/ux/components/model/test_repository.py | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 172 | 2021-09-14T18:34:17.000Z | 2022-03-30T06:49:53.000Z | test/ux/components/model/test_repository.py | intel/lp-opt-tool | 130eefa3586b38df6c0ff78cc8807ae273f6a63f | [
"Apache-2.0"
] | 40 | 2021-09-14T02:26:12.000Z | 2022-03-29T08:34:04.000Z | test/ux/components/model/test_repository.py | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 33 | 2021-09-15T07:27:25.000Z | 2022-03-25T08:30:57.000Z | # -*- coding: utf-8 -*-
# Copyright (c) 2021 Intel Corporation
#
# 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.
"""Test ModelRepository."""
import unittest
from neural_compressor.ux.components.model.repository import ModelRepository
from neural_compressor.ux.utils.consts import Frameworks
from neural_compressor.ux.utils.exceptions import NotFoundException
class TestModelRepository(unittest.TestCase):
"""Test ModelRepository class."""
def test_onnx_is_model_path(self) -> None:
"""Test if onnx file is recognized correctly."""
path = "/home/user/model.onnx"
result = ModelRepository.is_model_path(path)
self.assertTrue(result)
def test_mp3_is_model_path(self) -> None:
"""Test if mp3 file is recognized correctly."""
path = "/home/user/favourite_song.mp3"
result = ModelRepository.is_model_path(path)
self.assertFalse(result)
def test_get_frameworks(self) -> None:
"""Test getting frameworks."""
expected = [Frameworks.ONNX.value, Frameworks.TF.value]
repository = ModelRepository()
actual = repository.get_frameworks()
self.assertEqual(expected, actual)
def test_framework_from_path_for_known_model(self) -> None:
"""Test get_framework_from_path."""
actual = ModelRepository.get_framework_from_path("/home/user/model.onnx")
self.assertEqual(Frameworks.ONNX.value, actual)
def test_framework_from_path_for_unknown_model(self) -> None:
"""Test get_framework_from_path."""
with self.assertRaises(NotFoundException):
ModelRepository.get_framework_from_path("/home/user/favourite_song.mp3")
if __name__ == "__main__":
unittest.main()
| 36.47541 | 84 | 0.720899 |
import unittest
from neural_compressor.ux.components.model.repository import ModelRepository
from neural_compressor.ux.utils.consts import Frameworks
from neural_compressor.ux.utils.exceptions import NotFoundException
class TestModelRepository(unittest.TestCase):
def test_onnx_is_model_path(self) -> None:
path = "/home/user/model.onnx"
result = ModelRepository.is_model_path(path)
self.assertTrue(result)
def test_mp3_is_model_path(self) -> None:
path = "/home/user/favourite_song.mp3"
result = ModelRepository.is_model_path(path)
self.assertFalse(result)
def test_get_frameworks(self) -> None:
expected = [Frameworks.ONNX.value, Frameworks.TF.value]
repository = ModelRepository()
actual = repository.get_frameworks()
self.assertEqual(expected, actual)
def test_framework_from_path_for_known_model(self) -> None:
actual = ModelRepository.get_framework_from_path("/home/user/model.onnx")
self.assertEqual(Frameworks.ONNX.value, actual)
def test_framework_from_path_for_unknown_model(self) -> None:
with self.assertRaises(NotFoundException):
ModelRepository.get_framework_from_path("/home/user/favourite_song.mp3")
if __name__ == "__main__":
unittest.main()
| true | true |
f72c41f790310bb3e579547708ef92adbef03768 | 4,008 | py | Python | unit_test/test_interface.py | riven314/capstone_dash_interface | 5eab25f4c15ad09aa889554820231175b0a3ed28 | [
"CC0-1.0"
] | 1 | 2019-12-10T14:59:12.000Z | 2019-12-10T14:59:12.000Z | unit_test/test_interface.py | riven314/capstone_dash_interface | 5eab25f4c15ad09aa889554820231175b0a3ed28 | [
"CC0-1.0"
] | null | null | null | unit_test/test_interface.py | riven314/capstone_dash_interface | 5eab25f4c15ad09aa889554820231175b0a3ed28 | [
"CC0-1.0"
] | 1 | 2020-01-01T12:24:51.000Z | 2020-01-01T12:24:51.000Z | """
test the following:
model + scene understanding + interface
"""
import os
import sys
PATH = os.path.join(os.getcwd(), '..')
sys.path.append(PATH)
import cv2
from PyQt5.QtGui import QImage, QColor, QPixmap
from PyQt5.QtWidgets import QApplication
import qtmodern.styles
import qtmodern.windows
from layout import Layout
from pyqt_utils import convert_qimg
from scene_summary import get_names, create_grid, scene_summarize
from simplify_thread_utils import FrameStore, FrameThread
from obj_avoidance import run_avoidance
class SimplifyInteface(Layout):
def __init__(self):
super().__init__()
# setup for scene understanding
self.load_lightbulb()
self.mat = create_grid(h = 240, w = 427)
self.names = get_names()
self.init_thread()
def load_lightbulb(self):
RED_PATH = os.path.join('..', 'images', 'red.jpg')
GREEN_PATH = os.path.join('..', 'images', 'green.jpg')
assert os.path.isfile(RED_PATH), '[ERROR] Path not exist: {}'.format(RED_PATH)
assert os.path.isfile(GREEN_PATH), '[ERROR] Path not exist: {}'.format(GREEN_PATH)
red = cv2.imread(RED_PATH)
green = cv2.imread(GREEN_PATH)
self.red_qimg = convert_qimg(red, win_width = 50, win_height = 50)
self.green_qimg = convert_qimg(green, win_width = 50, win_height = 50)
def init_thread(self):
self.f_thread = FrameThread()
self.seg_names = self.f_thread.model_config.names
self.seg_colors = self.f_thread.model_config.colors
self.f_thread.frame_signal.connect(lambda frame_store: self.update_first_layer(frame_store))
self.f_thread.frame_signal.connect(lambda frame_store: self.update_second_layer(frame_store))
self.f_thread.frame_signal.connect(lambda frame_store: self.update_third_layer(frame_store))
self.f_thread.start()
def update_first_layer(self, frame_store):
"""
update different runtime and FPS
"""
self.model_time.setText('{0:.1f} ms'.format(frame_store.model_time * 1000))
self.fps_time.setText('{0:.1f}'.format(frame_store.fps_time))
def update_second_layer(self, frame_store):
"""
update segmentation result and scene summary
"""
# update segmentation result
qimg = convert_qimg(frame_store.pred_rgb, win_width = 620, win_height = 360)
self.seg_frame.setPixmap(QPixmap.fromImage(qimg))
# update scene summary
grid_dict = scene_summarize(frame_store.pred_idx,
self.mat, self.names,
threshold = 900)
self.update_scene_summary(grid_dict)
def update_scene_summary(self, grid_dict):
for i, obj_ls in grid_dict.items():
txt = ', '.join(obj_ls)
q_label = getattr(self, 'grid_{}'.format(i + 1))
q_label.setText(txt)
def update_third_layer(self, frame_store):
obj_tup, obj_img = run_avoidance(frame_store.d1_img, frame_store.pred_idx)
qimg = convert_qimg(obj_img, win_width = 620, win_height = 360, is_gray = True)
# update frame on left
self.obj_frame.setPixmap(QPixmap.fromImage(qimg))
# update summary on right
if obj_tup[1] is None:
self.obj_name.setText('NA')
self.obj_dist.setText('NA')
self.lightbulb.setPixmap(QPixmap.fromImage(self.green_qimg))
else:
obj_name = self.names[obj_tup[1] + 1]
self.obj_name.setText(obj_name)
self.obj_dist.setText('{} m'.format(obj_tup[2]))
self.lightbulb.setPixmap(QPixmap.fromImage(self.red_qimg))
if __name__ == '__main__':
app = QApplication(sys.argv)
win = SimplifyInteface()
qtmodern.styles.dark(app)
win_modern = qtmodern.windows.ModernWindow(win)
win_modern.show()
sys.exit(app.exec_())
| 38.538462 | 102 | 0.643214 | import os
import sys
PATH = os.path.join(os.getcwd(), '..')
sys.path.append(PATH)
import cv2
from PyQt5.QtGui import QImage, QColor, QPixmap
from PyQt5.QtWidgets import QApplication
import qtmodern.styles
import qtmodern.windows
from layout import Layout
from pyqt_utils import convert_qimg
from scene_summary import get_names, create_grid, scene_summarize
from simplify_thread_utils import FrameStore, FrameThread
from obj_avoidance import run_avoidance
class SimplifyInteface(Layout):
def __init__(self):
super().__init__()
self.load_lightbulb()
self.mat = create_grid(h = 240, w = 427)
self.names = get_names()
self.init_thread()
def load_lightbulb(self):
RED_PATH = os.path.join('..', 'images', 'red.jpg')
GREEN_PATH = os.path.join('..', 'images', 'green.jpg')
assert os.path.isfile(RED_PATH), '[ERROR] Path not exist: {}'.format(RED_PATH)
assert os.path.isfile(GREEN_PATH), '[ERROR] Path not exist: {}'.format(GREEN_PATH)
red = cv2.imread(RED_PATH)
green = cv2.imread(GREEN_PATH)
self.red_qimg = convert_qimg(red, win_width = 50, win_height = 50)
self.green_qimg = convert_qimg(green, win_width = 50, win_height = 50)
def init_thread(self):
self.f_thread = FrameThread()
self.seg_names = self.f_thread.model_config.names
self.seg_colors = self.f_thread.model_config.colors
self.f_thread.frame_signal.connect(lambda frame_store: self.update_first_layer(frame_store))
self.f_thread.frame_signal.connect(lambda frame_store: self.update_second_layer(frame_store))
self.f_thread.frame_signal.connect(lambda frame_store: self.update_third_layer(frame_store))
self.f_thread.start()
def update_first_layer(self, frame_store):
self.model_time.setText('{0:.1f} ms'.format(frame_store.model_time * 1000))
self.fps_time.setText('{0:.1f}'.format(frame_store.fps_time))
def update_second_layer(self, frame_store):
qimg = convert_qimg(frame_store.pred_rgb, win_width = 620, win_height = 360)
self.seg_frame.setPixmap(QPixmap.fromImage(qimg))
grid_dict = scene_summarize(frame_store.pred_idx,
self.mat, self.names,
threshold = 900)
self.update_scene_summary(grid_dict)
def update_scene_summary(self, grid_dict):
for i, obj_ls in grid_dict.items():
txt = ', '.join(obj_ls)
q_label = getattr(self, 'grid_{}'.format(i + 1))
q_label.setText(txt)
def update_third_layer(self, frame_store):
obj_tup, obj_img = run_avoidance(frame_store.d1_img, frame_store.pred_idx)
qimg = convert_qimg(obj_img, win_width = 620, win_height = 360, is_gray = True)
self.obj_frame.setPixmap(QPixmap.fromImage(qimg))
if obj_tup[1] is None:
self.obj_name.setText('NA')
self.obj_dist.setText('NA')
self.lightbulb.setPixmap(QPixmap.fromImage(self.green_qimg))
else:
obj_name = self.names[obj_tup[1] + 1]
self.obj_name.setText(obj_name)
self.obj_dist.setText('{} m'.format(obj_tup[2]))
self.lightbulb.setPixmap(QPixmap.fromImage(self.red_qimg))
if __name__ == '__main__':
app = QApplication(sys.argv)
win = SimplifyInteface()
qtmodern.styles.dark(app)
win_modern = qtmodern.windows.ModernWindow(win)
win_modern.show()
sys.exit(app.exec_())
| true | true |
f72c4215bb8a7b8efd6c3aee4ac1b1fb3af3b383 | 6,434 | py | Python | userbot/__init__.py | PRUDHVI-BOT/apple | daae0ca57f42c6a924a59bfd800b92e2a6c6115e | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/__init__.py | PRUDHVI-BOT/apple | daae0ca57f42c6a924a59bfd800b92e2a6c6115e | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/__init__.py | PRUDHVI-BOT/apple | daae0ca57f42c6a924a59bfd800b92e2a6c6115e | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot initialization. """
import os
from sys import version_info
from logging import basicConfig, getLogger, INFO, DEBUG
from distutils.util import strtobool as sb
from pylast import LastFMNetwork, md5
from pySmartDL import SmartDL
from dotenv import load_dotenv
from requests import get
from telethon import TelegramClient
from telethon.sessions import StringSession
load_dotenv("config.env")
# Bot Logs setup:
CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))
if CONSOLE_LOGGER_VERBOSE:
basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=DEBUG,
)
else:
basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=INFO)
LOGS = getLogger(__name__)
if version_info[0] < 3 or version_info[1] < 6:
LOGS.info("You MUST have a python version of at least 3.6."
"Multiple features depend on this. Bot quitting.")
quit(1)
# Check if the config was edited by using the already used variable.
# Basically, its the 'virginity check' for the config file ;)
CONFIG_CHECK = os.environ.get(
"___________PLOX_______REMOVE_____THIS_____LINE__________", None)
if CONFIG_CHECK:
LOGS.info(
"Please remove the line mentioned in the first hashtag from the config.env file"
)
quit(1)
# Telegram App KEY and HASH
API_KEY = os.environ.get("API_KEY", None)
API_HASH = os.environ.get("API_HASH", None)
# Userbot Session String
STRING_SESSION = os.environ.get("STRING_SESSION", None)
# Logging channel/group ID configuration.
BOTLOG_CHATID = int(os.environ.get("BOTLOG_CHATID", None))
# Userbot logging feature switch.
BOTLOG = sb(os.environ.get("BOTLOG", "False"))
LOGSPAMMER = sb(os.environ.get("LOGSPAMMER", "False"))
# Bleep Blop, this is a bot ;)
PM_AUTO_BAN = sb(os.environ.get("PM_AUTO_BAN", "False"))
# Console verbose logging
CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))
# SQL Database URI
DB_URI = os.environ.get("DATABASE_URL", None)
# OCR API key
OCR_SPACE_API_KEY = os.environ.get("OCR_SPACE_API_KEY", None)
# remove.bg API key
REM_BG_API_KEY = os.environ.get("REM_BG_API_KEY", None)
# Chrome Driver and Headless Google Chrome Binaries
CHROME_DRIVER = os.environ.get("CHROME_DRIVER", None)
GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN", None)
# OpenWeatherMap API Key
OPEN_WEATHER_MAP_APPID = os.environ.get("OPEN_WEATHER_MAP_APPID", None)
WEATHER_DEFCITY = os.environ.get("WEATHER_DEFCITY", None)
# Anti Spambot Config
ANTI_SPAMBOT = sb(os.environ.get("ANTI_SPAMBOT", "False"))
ANTI_SPAMBOT_SHOUT = sb(os.environ.get("ANTI_SPAMBOT_SHOUT", "False"))
# Youtube API key
YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY", None)
# Default .alive name
ALIVE_NAME = os.environ.get("ALIVE_NAME", None)
# Time & Date - Country and Time Zone
COUNTRY = str(os.environ.get("COUNTRY", ""))
TZ_NUMBER = int(os.environ.get("TZ_NUMBER", 1))
# Clean Welcome
CLEAN_WELCOME = sb(os.environ.get("CLEAN_WELCOME", "True"))
# Last.fm Module
BIO_PREFIX = os.environ.get("BIO_PREFIX", None)
DEFAULT_BIO = os.environ.get("DEFAULT_BIO", None)
LASTFM_API = os.environ.get("LASTFM_API", None)
LASTFM_SECRET = os.environ.get("LASTFM_SECRET", None)
LASTFM_USERNAME = os.environ.get("LASTFM_USERNAME", None)
LASTFM_PASSWORD_PLAIN = os.environ.get("LASTFM_PASSWORD", None)
if LASTFM_API and LASTFM_SECRET and LASTFM_USERNAME and LASTFM_PASSWORD_PLAIN:
LASTFM_PASS = md5(LASTFM_PASSWORD_PLAIN)
lastfm = LastFMNetwork(api_key=LASTFM_API,
api_secret=LASTFM_SECRET,
username=LASTFM_USERNAME,
password_hash=LASTFM_PASS)
else:
lastfm = None
# Google Drive Module configuration.
G_DRIVE_CLIENT_ID = os.environ.get("G_DRIVE_CLIENT_ID", None)
G_DRIVE_CLIENT_SECRET = os.environ.get("G_DRIVE_CLIENT_SECRET", None)
G_DRIVE_AUTH_TOKEN_DATA = os.environ.get("G_DRIVE_AUTH_TOKEN_DATA", None)
GDRIVE_FOLDER_ID = os.environ.get("GDRIVE_FOLDER_ID", None)
# Directory to save downloaded stuff, for many modules.
TEMP_DOWNLOAD_DIRECTORY = os.environ.get("TMP_DOWNLOAD_DIRECTORY",
"./downloads")
# Setting Up CloudMail.ru and MEGA.nz extractor binaries,
# and giving them correct perms to work properly.
if not os.path.exists('bin'):
os.mkdir('bin')
binaries = {
"https://raw.githubusercontent.com/yshalsager/megadown/master/megadown":
"bin/megadown",
"https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py":
"bin/cmrudl"
}
for binary, path in binaries.items():
downloader = SmartDL(binary, path, progress_bar=False)
downloader.start()
os.chmod(path, 0o755)
# 'bot' variable
if STRING_SESSION:
# pylint: disable=invalid-name
bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH, timeout=5, retry_delay=5)
else:
# pylint: disable=invalid-name
bot = TelegramClient("userbot", API_KEY, API_HASH, timeout=5, retry_delay=5)
async def check_botlog_chatid():
if not BOTLOG_CHATID and LOGSPAMMER:
LOGS.info(
"You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work."
)
quit(1)
elif not BOTLOG_CHATID and BOTLOG:
LOGS.info(
"You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the userbot logging feature to work."
)
quit(1)
elif not BOTLOG or not LOGSPAMMER:
return
entity = await bot.get_entity(BOTLOG_CHATID)
if entity.default_banned_rights.send_messages:
LOGS.info(
"Your account doesn't have rights to send messages to BOTLOG_CHATID "
"group. Check if you typed the Chat ID correctly.")
quit(1)
with bot:
try:
bot.loop.run_until_complete(check_botlog_chatid())
except:
LOGS.info(
"BOTLOG_CHATID environment variable isn't a "
"valid entity. Check your environment variables/config.env file.")
quit(1)
# Global Variables
COUNT_MSG = 0
USERS = {}
COUNT_PM = {}
LASTMSG = {}
CMD_HELP = {}
ISAFK = False
AFKREASON = None
| 32.17 | 143 | 0.713864 |
import os
from sys import version_info
from logging import basicConfig, getLogger, INFO, DEBUG
from distutils.util import strtobool as sb
from pylast import LastFMNetwork, md5
from pySmartDL import SmartDL
from dotenv import load_dotenv
from requests import get
from telethon import TelegramClient
from telethon.sessions import StringSession
load_dotenv("config.env")
CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))
if CONSOLE_LOGGER_VERBOSE:
basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=DEBUG,
)
else:
basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=INFO)
LOGS = getLogger(__name__)
if version_info[0] < 3 or version_info[1] < 6:
LOGS.info("You MUST have a python version of at least 3.6."
"Multiple features depend on this. Bot quitting.")
quit(1)
CONFIG_CHECK = os.environ.get(
"___________PLOX_______REMOVE_____THIS_____LINE__________", None)
if CONFIG_CHECK:
LOGS.info(
"Please remove the line mentioned in the first hashtag from the config.env file"
)
quit(1)
API_KEY = os.environ.get("API_KEY", None)
API_HASH = os.environ.get("API_HASH", None)
STRING_SESSION = os.environ.get("STRING_SESSION", None)
BOTLOG_CHATID = int(os.environ.get("BOTLOG_CHATID", None))
BOTLOG = sb(os.environ.get("BOTLOG", "False"))
LOGSPAMMER = sb(os.environ.get("LOGSPAMMER", "False"))
PM_AUTO_BAN = sb(os.environ.get("PM_AUTO_BAN", "False"))
CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))
DB_URI = os.environ.get("DATABASE_URL", None)
OCR_SPACE_API_KEY = os.environ.get("OCR_SPACE_API_KEY", None)
REM_BG_API_KEY = os.environ.get("REM_BG_API_KEY", None)
CHROME_DRIVER = os.environ.get("CHROME_DRIVER", None)
GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN", None)
OPEN_WEATHER_MAP_APPID = os.environ.get("OPEN_WEATHER_MAP_APPID", None)
WEATHER_DEFCITY = os.environ.get("WEATHER_DEFCITY", None)
ANTI_SPAMBOT = sb(os.environ.get("ANTI_SPAMBOT", "False"))
ANTI_SPAMBOT_SHOUT = sb(os.environ.get("ANTI_SPAMBOT_SHOUT", "False"))
YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY", None)
ALIVE_NAME = os.environ.get("ALIVE_NAME", None)
COUNTRY = str(os.environ.get("COUNTRY", ""))
TZ_NUMBER = int(os.environ.get("TZ_NUMBER", 1))
CLEAN_WELCOME = sb(os.environ.get("CLEAN_WELCOME", "True"))
BIO_PREFIX = os.environ.get("BIO_PREFIX", None)
DEFAULT_BIO = os.environ.get("DEFAULT_BIO", None)
LASTFM_API = os.environ.get("LASTFM_API", None)
LASTFM_SECRET = os.environ.get("LASTFM_SECRET", None)
LASTFM_USERNAME = os.environ.get("LASTFM_USERNAME", None)
LASTFM_PASSWORD_PLAIN = os.environ.get("LASTFM_PASSWORD", None)
if LASTFM_API and LASTFM_SECRET and LASTFM_USERNAME and LASTFM_PASSWORD_PLAIN:
LASTFM_PASS = md5(LASTFM_PASSWORD_PLAIN)
lastfm = LastFMNetwork(api_key=LASTFM_API,
api_secret=LASTFM_SECRET,
username=LASTFM_USERNAME,
password_hash=LASTFM_PASS)
else:
lastfm = None
G_DRIVE_CLIENT_ID = os.environ.get("G_DRIVE_CLIENT_ID", None)
G_DRIVE_CLIENT_SECRET = os.environ.get("G_DRIVE_CLIENT_SECRET", None)
G_DRIVE_AUTH_TOKEN_DATA = os.environ.get("G_DRIVE_AUTH_TOKEN_DATA", None)
GDRIVE_FOLDER_ID = os.environ.get("GDRIVE_FOLDER_ID", None)
TEMP_DOWNLOAD_DIRECTORY = os.environ.get("TMP_DOWNLOAD_DIRECTORY",
"./downloads")
if not os.path.exists('bin'):
os.mkdir('bin')
binaries = {
"https://raw.githubusercontent.com/yshalsager/megadown/master/megadown":
"bin/megadown",
"https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py":
"bin/cmrudl"
}
for binary, path in binaries.items():
downloader = SmartDL(binary, path, progress_bar=False)
downloader.start()
os.chmod(path, 0o755)
if STRING_SESSION:
bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH, timeout=5, retry_delay=5)
else:
bot = TelegramClient("userbot", API_KEY, API_HASH, timeout=5, retry_delay=5)
async def check_botlog_chatid():
if not BOTLOG_CHATID and LOGSPAMMER:
LOGS.info(
"You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work."
)
quit(1)
elif not BOTLOG_CHATID and BOTLOG:
LOGS.info(
"You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the userbot logging feature to work."
)
quit(1)
elif not BOTLOG or not LOGSPAMMER:
return
entity = await bot.get_entity(BOTLOG_CHATID)
if entity.default_banned_rights.send_messages:
LOGS.info(
"Your account doesn't have rights to send messages to BOTLOG_CHATID "
"group. Check if you typed the Chat ID correctly.")
quit(1)
with bot:
try:
bot.loop.run_until_complete(check_botlog_chatid())
except:
LOGS.info(
"BOTLOG_CHATID environment variable isn't a "
"valid entity. Check your environment variables/config.env file.")
quit(1)
COUNT_MSG = 0
USERS = {}
COUNT_PM = {}
LASTMSG = {}
CMD_HELP = {}
ISAFK = False
AFKREASON = None
| true | true |
f72c4479ad5d2532a05900a83c5526eec00f800e | 13,381 | py | Python | src/rkd_harbor/tasks/deployment/base.py | attawayinc/riotkit-harbor | baea9f6e856f18835d316e3adc01ced2b9aaebda | [
"Apache-2.0"
] | 14 | 2019-04-12T11:24:54.000Z | 2022-03-21T01:13:27.000Z | src/rkd_harbor/tasks/deployment/base.py | attawayinc/riotkit-harbor | baea9f6e856f18835d316e3adc01ced2b9aaebda | [
"Apache-2.0"
] | 37 | 2019-06-29T05:54:10.000Z | 2021-08-03T05:54:52.000Z | src/rkd_harbor/tasks/deployment/base.py | attawayinc/riotkit-harbor | baea9f6e856f18835d316e3adc01ced2b9aaebda | [
"Apache-2.0"
] | 2 | 2021-09-29T04:22:52.000Z | 2021-09-29T06:43:59.000Z | import os
import subprocess
from abc import ABC
from jinja2 import Environment
from jinja2 import FileSystemLoader
from jinja2 import StrictUndefined
from jinja2.exceptions import UndefinedError
from argparse import ArgumentParser
from rkd.api.contract import ExecutionContext
from rkd.yaml_parser import YamlFileLoader
from rkd.exception import MissingInputException
from rkd.api.inputoutput import Wizard
from ..base import HarborBaseTask
from ...exception import MissingDeploymentConfigurationError
HARBOR_ROOT = os.path.dirname(os.path.realpath(__file__)) + '/../../deployment/files'
class BaseDeploymentTask(HarborBaseTask, ABC):
ansible_dir: str = '.rkd/deployment'
_config: dict
vault_args: list = []
def get_config(self) -> dict:
"""Loads and parses deployment.yml file.
Supports:
- Ansible Vault encryption of deployment.yml
- SSH private key storage inside deployment.yml
"""
deployment_filenames = ['deployment.yml', 'deployment.yaml']
try:
self._config
except AttributeError:
# try multiple files
for filename in deployment_filenames:
if os.path.isfile(filename):
#
# Check file contents before
#
with open(filename, 'rb') as f:
content = f.read().decode('utf-8')
#
# When file is encrypted, then decrypt it
#
if content.startswith('$ANSIBLE_VAULT;'):
tmp_vault_path, tmp_vault_filename = self.temp.create_tmp_file_path()
self.io().info('Decrypting deployment file')
self.sh('cp %s %s' % (filename, tmp_vault_path))
self.io().info_msg('Need a vault passphrase to decrypt "%s"' % filename)
self.rkd([':harbor:vault:encrypt', '-d', tmp_vault_path] + self.vault_args)
self._config = YamlFileLoader(self._ctx.directories).load_from_file(
tmp_vault_filename,
'org.riotkit.harbor/deployment/v1'
)
self._process_config_private_keys()
return self._config
self._config = YamlFileLoader(self._ctx.directories).load_from_file(
filename,
'org.riotkit.harbor/deployment/v1'
)
self._process_config_private_keys()
return self._config
raise MissingDeploymentConfigurationError()
return self._config
def _process_config_private_keys(self):
"""Allow private keys to be pasted directly to the deployment.yml
On-the-fly those keys will be written into the temporary directory
"""
for group_name, nodes in self._config['nodes'].items():
for node_num in range(0, len(nodes)):
if 'private_key' not in self._config['nodes'][group_name][node_num]:
continue
if '-----BEGIN' not in self._config['nodes'][group_name][node_num]['private_key']:
continue
tmp_path = self.temp.assign_temporary_file(mode=0o700)
self.io().info('Storing inline private key as "%s"' % tmp_path)
with open(tmp_path, 'w') as key_file:
key_file.write(self._config['nodes'][group_name][node_num]['private_key'].strip())
key_file.write("\n")
self._config['nodes'][group_name][node_num]['private_key'] = tmp_path
def _verify_synced_version(self, abs_ansible_dir: str):
"""Verifies last synchronization - displays warning if Harbor version was changed after last
files synchronization"""
if not os.path.isfile(abs_ansible_dir + '/.synced'):
return
with open(abs_ansible_dir + '/.synced', 'rb') as f:
synced_version = f.read().decode('utf-8').strip()
actual_version = self.get_harbor_version()
if synced_version != actual_version:
self.io().warn('Ansible deployment in .rkd/deployment is not up-to-date. We recommend to update' +
' from %s to %s' % (synced_version, actual_version))
def _write_synced_version(self, abs_ansible_dir: str):
"""Writes information about, in which Harbor version the files were synced last time"""
with open(abs_ansible_dir + '/.synced', 'wb') as f:
f.write(self.get_harbor_version().encode('utf-8'))
def role_is_installed_and_configured(self) -> bool:
return os.path.isfile(self.ansible_dir + '/.synced')
def _ask_and_set_var(self, ctx: ExecutionContext, arg_name: str, title: str, attribute: str, secret: bool):
"""Ask user an interactive question, then add answer to the deployment.yml loaded in memory
The variable will be appended to any node, where the variable is empty.
Example: We have 5 servers, 3 without a password. So the password will be applied to 3 servers.
"""
self.get_config()
if not ctx.get_arg(arg_name):
return
wizard = Wizard(self).ask(title, attribute=attribute, secret=secret)
for group_name, nodes in self._config['nodes'].items():
node_num = 0
for node in nodes:
node_num += 1
if attribute in self._config['nodes'][group_name][node_num - 1]:
continue
self._config['nodes'][group_name][node_num - 1][attribute] = wizard.answers[attribute]
def install_and_configure_role(self, ctx: ExecutionContext, force_update: bool = False) -> bool:
"""Install an Ansible role from galaxy, and configure playbook, inventory, all the needed things"""
abs_ansible_dir = os.path.realpath(self.ansible_dir)
should_update = force_update or not os.path.isfile(abs_ansible_dir + '/.synced')
self.io().info('Checking role installation...')
self._silent_mkdir(abs_ansible_dir)
self._verify_synced_version(abs_ansible_dir)
# optionally ask user and set facts such as passwords, key paths, sudo passwords
# ansible-vault password prompt is handed by ansible-vault itself
self._ask_and_set_var(ctx, '--ask-ssh-login', 'SSH username', 'user', secret=True)
self._ask_and_set_var(ctx, '--ask-ssh-pass', 'SSH password', 'password', secret=True)
self._ask_and_set_var(ctx, '--ask-ssh-key-path', 'SSH private key path', 'private_key', secret=False)
self._ask_and_set_var(ctx, '--ask-sudo-pass', 'Sudo password for remote machines', 'sudo_pass', secret=True)
if not self._synchronize_structure_from_template(abs_ansible_dir, only_jinja_templates=True):
self.io().error_msg('Cannot synchronize templates')
return False
if should_update:
self.io().info('Role will be updated')
if not self._synchronize_structure_from_template(abs_ansible_dir):
self.io().error_msg('Cannot synchronize structure')
return False
self.io().debug('Downloading fresh role...')
self.download_roles()
self._write_synced_version(abs_ansible_dir)
return True
def download_roles(self):
self.sh(' '.join([
'ansible-galaxy',
'install', '-r', self.ansible_dir + '/requirements.yml',
'-p', self.ansible_dir + '/roles/',
'--force'
]), capture=False)
def _synchronize_structure_from_template(self, abs_ansible_dir: str, only_jinja_templates: bool = False) -> bool:
"""Synchronizes template structure into .rkd/deployment"""
self.io().debug(
'Synchronizing structure from template (only_jinja_templates=' + str(only_jinja_templates) + ')')
# synchronize directory structure
for root, subdirs, files in os.walk(HARBOR_ROOT):
relative_root = root[len(HARBOR_ROOT) + 1:]
self._silent_mkdir(abs_ansible_dir + '/' + relative_root)
for file in files:
if only_jinja_templates and not file.endswith('.j2'):
continue
abs_src_file_path = root + '/' + file
abs_dest_file_path = abs_ansible_dir + '/' + relative_root + '/' + file
if not self._copy_file(abs_src_file_path, abs_dest_file_path):
self.io().error('Cannot process file %s' % abs_dest_file_path)
return False
return True
def _copy_file(self, abs_src_file_path: str, abs_dest_file_path: str):
"""Copies a file from template directory - supports jinja2 files rendering on-the-fly"""
if abs_dest_file_path.endswith('.j2'):
abs_dest_file_path = abs_dest_file_path[:-3]
with open(abs_src_file_path, 'rb') as f:
tpl = Environment(loader=FileSystemLoader(['./', './rkd/deployment']), undefined=StrictUndefined)\
.from_string(f.read().decode('utf-8'))
try:
variables = self._prepare_variables()
with open(abs_dest_file_path, 'wb') as f:
f.write(tpl.render(**variables).encode('utf-8'))
except UndefinedError as e:
self.io().error(str(e) + " - required in " + abs_src_file_path + ", please define it in deployment.yml")
return False
return True
subprocess.check_call(['cp', '-p', abs_src_file_path, abs_dest_file_path])
self.io().debug('Created ' + abs_dest_file_path)
return True
def _prepare_variables(self):
"""Glues together variables from environment and from deployment.yaml for exposing in JINJA2 templates"""
variables = {}
variables.update(os.environ)
variables.update(self.get_config())
if 'git_url' not in variables:
variables['git_url'] = subprocess\
.check_output(['git', 'config', '--get', 'remote.origin.url']).decode('utf-8')\
.replace('\n', '')\
.strip()
if 'git_secret_url' not in variables:
variables['git_secret_url'] = variables['git_url'].replace('\n', '')
return variables
def _preserve_vault_parameters_for_usage_in_inner_tasks(self, ctx: ExecutionContext):
"""Preserve original parameters related to Vault, so those parameters can be propagated to inner tasks"""
try:
vault_passwords = ctx.get_arg_or_env('--vault-passwords')
except MissingInputException:
vault_passwords = ''
# keep the vault arguments for decryption of deployment.yml
self.vault_args = ['--vault-passwords=' + vault_passwords]
if ctx.get_arg('--ask-vault-pass'):
self.vault_args.append('--ask-vault-pass')
def _get_vault_opts(self, ctx: ExecutionContext, chdir: str = '') -> str:
"""Creates options to pass in Ansible Vault commandline
The output will be a temporary vault file with password entered inline or a --ask-vault-pass switch
"""
try:
vault_passwords = ctx.get_arg_or_env('--vault-passwords').split('||')
except MissingInputException:
vault_passwords = []
num = 0
opts = ''
enforce_ask_pass = ctx.get_arg('--ask-vault-pass')
for passwd in vault_passwords:
num = num + 1
if not passwd:
continue
if passwd.startswith('./') or passwd.startswith('/'):
if os.path.isfile(passwd):
opts += ' --vault-password-file="%s" ' % (chdir + passwd)
else:
self.io().error('Vault password file "%s" does not exist, calling --ask-vault-pass' % passwd)
enforce_ask_pass = True
else:
tmp_vault_file = self.temp.assign_temporary_file(mode=0o644)
with open(tmp_vault_file, 'w') as f:
f.write(passwd)
opts += ' --vault-password-file="%s" ' % (chdir + tmp_vault_file)
if enforce_ask_pass:
opts += ' --ask-vault-pass '
return opts
@classmethod
def _add_vault_arguments_to_argparse(cls, parser: ArgumentParser):
parser.add_argument('--ask-vault-pass', '-v', help='Ask for vault password interactively', action='store_true')
parser.add_argument('--vault-passwords', '-V', help='Vault passwords separated by "||" eg. 123||456')
@classmethod
def _add_ask_pass_arguments_to_argparse(cls, parser: ArgumentParser):
parser.add_argument('--ask-ssh-login', help='Ask for SSH username', action='store_true')
parser.add_argument('--ask-ssh-pass', help='Ask for a SSH password', action='store_true')
parser.add_argument('--ask-ssh-key-path', help='Ask for a SSH private key path', action='store_true')
parser.add_argument('--ask-sudo-pass', help='Ask for sudo password', action='store_true')
| 41.172308 | 120 | 0.603318 | import os
import subprocess
from abc import ABC
from jinja2 import Environment
from jinja2 import FileSystemLoader
from jinja2 import StrictUndefined
from jinja2.exceptions import UndefinedError
from argparse import ArgumentParser
from rkd.api.contract import ExecutionContext
from rkd.yaml_parser import YamlFileLoader
from rkd.exception import MissingInputException
from rkd.api.inputoutput import Wizard
from ..base import HarborBaseTask
from ...exception import MissingDeploymentConfigurationError
HARBOR_ROOT = os.path.dirname(os.path.realpath(__file__)) + '/../../deployment/files'
class BaseDeploymentTask(HarborBaseTask, ABC):
ansible_dir: str = '.rkd/deployment'
_config: dict
vault_args: list = []
def get_config(self) -> dict:
deployment_filenames = ['deployment.yml', 'deployment.yaml']
try:
self._config
except AttributeError:
for filename in deployment_filenames:
if os.path.isfile(filename):
with open(filename, 'rb') as f:
content = f.read().decode('utf-8')
if content.startswith('$ANSIBLE_VAULT;'):
tmp_vault_path, tmp_vault_filename = self.temp.create_tmp_file_path()
self.io().info('Decrypting deployment file')
self.sh('cp %s %s' % (filename, tmp_vault_path))
self.io().info_msg('Need a vault passphrase to decrypt "%s"' % filename)
self.rkd([':harbor:vault:encrypt', '-d', tmp_vault_path] + self.vault_args)
self._config = YamlFileLoader(self._ctx.directories).load_from_file(
tmp_vault_filename,
'org.riotkit.harbor/deployment/v1'
)
self._process_config_private_keys()
return self._config
self._config = YamlFileLoader(self._ctx.directories).load_from_file(
filename,
'org.riotkit.harbor/deployment/v1'
)
self._process_config_private_keys()
return self._config
raise MissingDeploymentConfigurationError()
return self._config
def _process_config_private_keys(self):
for group_name, nodes in self._config['nodes'].items():
for node_num in range(0, len(nodes)):
if 'private_key' not in self._config['nodes'][group_name][node_num]:
continue
if '-----BEGIN' not in self._config['nodes'][group_name][node_num]['private_key']:
continue
tmp_path = self.temp.assign_temporary_file(mode=0o700)
self.io().info('Storing inline private key as "%s"' % tmp_path)
with open(tmp_path, 'w') as key_file:
key_file.write(self._config['nodes'][group_name][node_num]['private_key'].strip())
key_file.write("\n")
self._config['nodes'][group_name][node_num]['private_key'] = tmp_path
def _verify_synced_version(self, abs_ansible_dir: str):
if not os.path.isfile(abs_ansible_dir + '/.synced'):
return
with open(abs_ansible_dir + '/.synced', 'rb') as f:
synced_version = f.read().decode('utf-8').strip()
actual_version = self.get_harbor_version()
if synced_version != actual_version:
self.io().warn('Ansible deployment in .rkd/deployment is not up-to-date. We recommend to update' +
' from %s to %s' % (synced_version, actual_version))
def _write_synced_version(self, abs_ansible_dir: str):
with open(abs_ansible_dir + '/.synced', 'wb') as f:
f.write(self.get_harbor_version().encode('utf-8'))
def role_is_installed_and_configured(self) -> bool:
return os.path.isfile(self.ansible_dir + '/.synced')
def _ask_and_set_var(self, ctx: ExecutionContext, arg_name: str, title: str, attribute: str, secret: bool):
self.get_config()
if not ctx.get_arg(arg_name):
return
wizard = Wizard(self).ask(title, attribute=attribute, secret=secret)
for group_name, nodes in self._config['nodes'].items():
node_num = 0
for node in nodes:
node_num += 1
if attribute in self._config['nodes'][group_name][node_num - 1]:
continue
self._config['nodes'][group_name][node_num - 1][attribute] = wizard.answers[attribute]
def install_and_configure_role(self, ctx: ExecutionContext, force_update: bool = False) -> bool:
abs_ansible_dir = os.path.realpath(self.ansible_dir)
should_update = force_update or not os.path.isfile(abs_ansible_dir + '/.synced')
self.io().info('Checking role installation...')
self._silent_mkdir(abs_ansible_dir)
self._verify_synced_version(abs_ansible_dir)
self._ask_and_set_var(ctx, '--ask-ssh-login', 'SSH username', 'user', secret=True)
self._ask_and_set_var(ctx, '--ask-ssh-pass', 'SSH password', 'password', secret=True)
self._ask_and_set_var(ctx, '--ask-ssh-key-path', 'SSH private key path', 'private_key', secret=False)
self._ask_and_set_var(ctx, '--ask-sudo-pass', 'Sudo password for remote machines', 'sudo_pass', secret=True)
if not self._synchronize_structure_from_template(abs_ansible_dir, only_jinja_templates=True):
self.io().error_msg('Cannot synchronize templates')
return False
if should_update:
self.io().info('Role will be updated')
if not self._synchronize_structure_from_template(abs_ansible_dir):
self.io().error_msg('Cannot synchronize structure')
return False
self.io().debug('Downloading fresh role...')
self.download_roles()
self._write_synced_version(abs_ansible_dir)
return True
def download_roles(self):
self.sh(' '.join([
'ansible-galaxy',
'install', '-r', self.ansible_dir + '/requirements.yml',
'-p', self.ansible_dir + '/roles/',
'--force'
]), capture=False)
def _synchronize_structure_from_template(self, abs_ansible_dir: str, only_jinja_templates: bool = False) -> bool:
self.io().debug(
'Synchronizing structure from template (only_jinja_templates=' + str(only_jinja_templates) + ')')
for root, subdirs, files in os.walk(HARBOR_ROOT):
relative_root = root[len(HARBOR_ROOT) + 1:]
self._silent_mkdir(abs_ansible_dir + '/' + relative_root)
for file in files:
if only_jinja_templates and not file.endswith('.j2'):
continue
abs_src_file_path = root + '/' + file
abs_dest_file_path = abs_ansible_dir + '/' + relative_root + '/' + file
if not self._copy_file(abs_src_file_path, abs_dest_file_path):
self.io().error('Cannot process file %s' % abs_dest_file_path)
return False
return True
def _copy_file(self, abs_src_file_path: str, abs_dest_file_path: str):
if abs_dest_file_path.endswith('.j2'):
abs_dest_file_path = abs_dest_file_path[:-3]
with open(abs_src_file_path, 'rb') as f:
tpl = Environment(loader=FileSystemLoader(['./', './rkd/deployment']), undefined=StrictUndefined)\
.from_string(f.read().decode('utf-8'))
try:
variables = self._prepare_variables()
with open(abs_dest_file_path, 'wb') as f:
f.write(tpl.render(**variables).encode('utf-8'))
except UndefinedError as e:
self.io().error(str(e) + " - required in " + abs_src_file_path + ", please define it in deployment.yml")
return False
return True
subprocess.check_call(['cp', '-p', abs_src_file_path, abs_dest_file_path])
self.io().debug('Created ' + abs_dest_file_path)
return True
def _prepare_variables(self):
variables = {}
variables.update(os.environ)
variables.update(self.get_config())
if 'git_url' not in variables:
variables['git_url'] = subprocess\
.check_output(['git', 'config', '--get', 'remote.origin.url']).decode('utf-8')\
.replace('\n', '')\
.strip()
if 'git_secret_url' not in variables:
variables['git_secret_url'] = variables['git_url'].replace('\n', '')
return variables
def _preserve_vault_parameters_for_usage_in_inner_tasks(self, ctx: ExecutionContext):
try:
vault_passwords = ctx.get_arg_or_env('--vault-passwords')
except MissingInputException:
vault_passwords = ''
self.vault_args = ['--vault-passwords=' + vault_passwords]
if ctx.get_arg('--ask-vault-pass'):
self.vault_args.append('--ask-vault-pass')
def _get_vault_opts(self, ctx: ExecutionContext, chdir: str = '') -> str:
try:
vault_passwords = ctx.get_arg_or_env('--vault-passwords').split('||')
except MissingInputException:
vault_passwords = []
num = 0
opts = ''
enforce_ask_pass = ctx.get_arg('--ask-vault-pass')
for passwd in vault_passwords:
num = num + 1
if not passwd:
continue
if passwd.startswith('./') or passwd.startswith('/'):
if os.path.isfile(passwd):
opts += ' --vault-password-file="%s" ' % (chdir + passwd)
else:
self.io().error('Vault password file "%s" does not exist, calling --ask-vault-pass' % passwd)
enforce_ask_pass = True
else:
tmp_vault_file = self.temp.assign_temporary_file(mode=0o644)
with open(tmp_vault_file, 'w') as f:
f.write(passwd)
opts += ' --vault-password-file="%s" ' % (chdir + tmp_vault_file)
if enforce_ask_pass:
opts += ' --ask-vault-pass '
return opts
@classmethod
def _add_vault_arguments_to_argparse(cls, parser: ArgumentParser):
parser.add_argument('--ask-vault-pass', '-v', help='Ask for vault password interactively', action='store_true')
parser.add_argument('--vault-passwords', '-V', help='Vault passwords separated by "||" eg. 123||456')
@classmethod
def _add_ask_pass_arguments_to_argparse(cls, parser: ArgumentParser):
parser.add_argument('--ask-ssh-login', help='Ask for SSH username', action='store_true')
parser.add_argument('--ask-ssh-pass', help='Ask for a SSH password', action='store_true')
parser.add_argument('--ask-ssh-key-path', help='Ask for a SSH private key path', action='store_true')
parser.add_argument('--ask-sudo-pass', help='Ask for sudo password', action='store_true')
| true | true |
f72c4540917b51bca7ea46963d819966d9f4ad33 | 103 | py | Python | code/test/__init__.py | fgitmichael/TestModeDisentangling | 022fbe5b49e847aeb110d89be1e0b1c28bcff01d | [
"MIT"
] | 1 | 2020-05-16T14:03:09.000Z | 2020-05-16T14:03:09.000Z | code/test/__init__.py | fgitmichael/TestModeDisentangling | 022fbe5b49e847aeb110d89be1e0b1c28bcff01d | [
"MIT"
] | null | null | null | code/test/__init__.py | fgitmichael/TestModeDisentangling | 022fbe5b49e847aeb110d89be1e0b1c28bcff01d | [
"MIT"
] | null | null | null | from .mode_actions_sampler import ModeActionSampler
from .disentangling_test import DisentanglingTester | 51.5 | 51 | 0.912621 | from .mode_actions_sampler import ModeActionSampler
from .disentangling_test import DisentanglingTester | true | true |
f72c462c3af80843d61e6f49c7378e99c77bb19c | 22,921 | py | Python | src/plant_energyse/openwind/academic/openWindAcComponent.py | WISDEM/Plant_EnergySE | 5ca898bf65b63fd1a87a40241591866f5f0b185a | [
"Apache-2.0"
] | 1 | 2019-02-26T17:54:14.000Z | 2019-02-26T17:54:14.000Z | src/plant_energyse/openwind/academic/openWindAcComponent.py | WISDEM/Plant_EnergySE | 5ca898bf65b63fd1a87a40241591866f5f0b185a | [
"Apache-2.0"
] | null | null | null | src/plant_energyse/openwind/academic/openWindAcComponent.py | WISDEM/Plant_EnergySE | 5ca898bf65b63fd1a87a40241591866f5f0b185a | [
"Apache-2.0"
] | 1 | 2021-04-19T18:40:39.000Z | 2021-04-19T18:40:39.000Z | # openWindAcComponent.py
# 2014 04 08
'''
Execute OpenWindAcademic as an OpenMDAO Component
After execute(), the following variables have been updated:
nTurbs
net_aep
gross_aep
They can be accessed through appropriate connections.
NOTE: Script file must contain an Optimize/Optimise operation - otherwise,
no results will be found.
Typical use (e.g., from an Assembly):
owac = OWACcomp(owExe, scriptFile=scrptName, debug=False, stopOW=True, start_once=False, opt_log=False)
main() runs OWACcomp.execute() 3 times, moving and modifying the turbines each time
'''
import os.path
import sys, time
import subprocess
from lxml import etree
import owAcademicUtils as acutils
import plant_energyse.openwind.openWindUtils as utils
import plant_energyse.openwind.rwScriptXML as rwScriptXML
import plant_energyse.openwind.rwTurbXML as rwTurbXML
import plant_energyse.openwind.turbfuncs as turbfuncs
from openmdao.lib.datatypes.api import Float, Int, VarTree
from openmdao.main.api import FileMetadata, Component, VariableTree
from fusedwind.plant_flow.vt import GenericWindTurbineVT, \
GenericWindTurbinePowerCurveVT, ExtendedWindTurbinePowerCurveVT, \
GenericWindFarmTurbineLayout, ExtendedWindFarmTurbineLayout
from fusedwind.interface import implement_base
from fusedwind.plant_flow.comp import BaseAEPAggregator
#-----------------------------------------------------------------
@implement_base(BaseAEPAggregator)
class OWACcomp(Component):
""" A simple OpenMDAO component for OpenWind academic
Args:
owExe (str): full path to OpenWind executable
scriptFile (str): path to XML script that OpenWind will run
"""
# inputs
rotor_diameter = Float(126.0, iotype='in', units='m', desc='connecting rotor diameter to force run on change') # todo: hack for now
availability = Float(0.95, iotype='in', desc='availability')
other_losses = Float(0.0, iotype='in', desc='soiling losses')
wt_layout = VarTree(ExtendedWindFarmTurbineLayout(), iotype='in', desc='properties for each wind turbine and layout')
dummyVbl = Float(0, iotype='in', desc='unused variable to make it easy to do DOE runs')
# outputs
gross_aep = Float(0.0, iotype='out', desc='Gross Output')
net_aep = Float(0.0, iotype='out', desc='Net Output')
nTurbs = Int(0, iotype='out', desc='Number of turbines')
#array_aep = Float(0.0, iotype='out', desc='Array output - NOT USED IN ACADEMIC VERSION')
#array_efficiency = Float(0.0, iotype='out', desc='Array Efficiency')
#array_losses = Float(0.0, iotype='out', desc='Array losses')
def __init__(self, owExe, scriptFile=None, debug=False, stopOW=True, start_once=False, opt_log=False):
""" Constructor for the OWACwrapped component """
self.debug = debug
if self.debug:
sys.stderr.write('\nIn {:}.__init__()\n'.format(self.__class__))
super(OWACcomp, self).__init__()
# public variables
self.input_file = 'myinput.txt'
self.output_file = 'myoutput.txt'
self.stderr = 'myerror.log'
# external_files : member of Component class = list of FileMetadata objects
self.external_files = [
FileMetadata(path=self.output_file),
FileMetadata(path=self.stderr),
]
self.stopOW = stopOW
self.start_once = start_once
self.replace_turbine = False
self.opt_log = opt_log
self.resname = '' # start with empty string
self.script_file = scriptFile
self.scriptOK = False
if scriptFile is not None:
# Check script file for validity and extract some path information
self.scriptOK = self.parse_scriptFile()
if not self.scriptOK:
raise ValueError
return
self.scriptDict = rwScriptXML.rdScript(self.script_file, self.debug)
if self.debug:
sys.stderr.write('Script File Contents:\n')
for k in self.scriptDict.keys():
sys.stderr.write(' {:12s} {:}\n'.format(k,self.scriptDict[k]))
# Log all optimization settings?
if self.opt_log:
self.olname = 'owacOptLog.txt'
self.olfh = open(self.olname, 'w')
if self.debug:
sys.stderr.write('Logging optimization params to {:}\n'.format(self.olname))
# Set the version of OpenWind that we want to use
self.command = [owExe, self.script_file]
# Keep the initial value of rotor diam so we can
# see if it (or other turb param) has changed
self.rtr_diam_init = self.rotor_diameter
# ... other params ....
# Try starting OpenWind here (if self.start_once is True)
if self.start_once:
self.proc = subprocess.Popen(self.command)
self.pid = self.proc.pid
if self.debug:
sys.stderr.write('Started OpenWind with pid {:}\n'.format(self.pid))
sys.stderr.write(' OWACComp: dummyVbl {:}\n'.format(self.dummyVbl))
if self.debug:
sys.stderr.write('\nLeaving {:}.__init__()\n'.format(self.__class__))
#------------------
def parse_scriptFile(self):
# OWac looks for the notify files and writes the 'results.txt' file to the
# directory that contains the *blb workbook file
# Find where the results file will be found
if not os.path.isfile(self.script_file):
sys.stderr.write('\n*** OpenWind script file "{:}" not found\n'.format(self.script_file))
return False
try:
e = etree.parse(self.script_file)
self.rptpath = e.getroot().find('ReportPath').get('value')
except:
sys.stderr.write("\n*** Can't find ReportPath in {:}\n".format(self.script_file))
self.rptpath = 'NotFound'
return False
# Make sure there's an optimize operation - otherwise OWAC won't find anything
foundOpt = False
self.replace_turbine = False
ops = e.getroot().findall('.//Operation')
for op in ops:
optype = op.find('Type').get('value')
if optype == 'Optimize' or optype == 'Optimise':
foundOpt = True
break
if optype == 'Replace Turbine Type':
self.replace_turbine = True
sys.stderr.write('\n*** WARNING: start_once will be set to False because Replace Turbine\n')
sys.stderr.write(' operation is present in {:}\n\n'.format(self.script_file))
self.start_once = False
if not foundOpt:
sys.stderr.write('\n*** ERROR: no Optimize operation found in {:}\n\n'.format(self.script_file))
return False
if self.replace_turbine and self.start_once:
sys.stderr.write("*** WARNING: can't use start_once when replacing turbine\n")
sys.stderr.write(" setting start_once to False\n")
self.start_once = False
# Find the workbook folder and save as dname
self.dname = None
for op in ops:
if op.find('Type').get('value') == 'Change Workbook':
wkbk = op.find('Path').get('value')
if not os.path.isfile(wkbk):
sys.stderr.write("\n*** OpenWind workbook file {:}\n not found\n".format(wkbk))
sys.stderr.write(" (specified in script file {:})\n".format(self.script_file))
return False
self.dname = os.path.dirname(wkbk)
if self.debug:
sys.stderr.write('Working directory: {:}\n'.format(self.dname))
break
self.resname = '/'.join([self.dname,'results.txt'])
return True
#------------------
def execute(self):
""" Executes our component. """
if self.debug:
sys.stderr.write(" In {0}.execute() {1}...\n".format(self.__class__, self.script_file))
if (len(self.resname) < 1):
sys.stderr.write('\n*** ERROR: OWAcomp results file name not assigned! (problem with script file?)\n\n')
return False
# Prepare input file here
# - write a new script file?
# - write a new turbine file to overwrite the one referenced
# in the existing script_file?
# If there is a turbine replacement operation in the script:
# write new turbine description file based on contents of first turbine in layout
#if 'replturbpath' in self.scriptDict:
if self.replace_turbine:
if len(self.wt_layout.wt_list) < 1:
sys.stderr.write('\n*** ERROR *** OWACcomp::execute(): no turbines in wt_layout!\n\n')
return False
if self.debug:
sys.stderr.write('Replacement turbine parameters:\n')
#sys.stderr.write('{:}\n'.format(turbfuncs.wtpc_dump(self.wt_layout.wt_list[0])))
sys.stderr.write('{:}\n'.format(turbfuncs.wtpc_dump(self.wt_layout.wt_list[0], shortFmt=True)))
#sys.stderr.write('{:}\n'.format(wtlDump(self.wt_layout.wt_list[0])))
newXML = turbfuncs.wtpc_to_owtg(self.wt_layout.wt_list[0],
trbname='ReplTurb',
desc='OWACcomp replacement turbine')
if len(newXML) > 50:
tfname = self.scriptDict['replturbpath'] # this is the file that will be overwritten with new turbine parameters
tfh = open(tfname, 'w')
tfh.write(newXML)
tfh.close()
maxPower = self.wt_layout.wt_list[0].power_rating
if self.debug:
sys.stderr.write('Wrote new turbine file to {:} (rated pwr {:.2f} MW\n'.format(tfname, maxPower*0.000001))
else:
sys.stderr.write('*** NO new turbine file written\n')
# Execute the component and save process ID
if not self.start_once:
self.proc = subprocess.Popen(self.command)
self.pid = self.proc.pid
if self.debug:
sys.stderr.write('Started OpenWind with pid {:}\n'.format(self.pid))
sys.stderr.write(' OWACComp: dummyVbl {:}\n'.format(self.dummyVbl))
#sys.stderr.write('Report Path: {:}\n'.format(self.rptpath))
# Watch for 'results.txt', meaning that OW has run once with the default locations
if self.debug:
sys.stderr.write('OWACComp waiting for {:} (first run - positions unchanged)\n'.format(self.resname))
acutils.waitForNotify(watchFile=self.resname, path=self.dname, debug=False, callback=self.getCBvalue)
# Now OWac is waiting for a new position file
# Write new positions and notify file - this time it should use updated positions
acutils.writePositionFile(self.wt_layout.wt_positions, path=self.dname, debug=self.debug)
# see if results.txt is there already
if os.path.exists(self.resname):
resmtime = os.path.getmtime(self.resname)
if self.debug:
sys.stderr.write('ModTime({:}): {:}\n'.format(self.resname, time.asctime(time.localtime(resmtime))))
else:
if self.debug:
sys.stderr.write('{:} does not exist yet\n'.format(self.resname))
acutils.writeNotify(path=self.dname, debug=self.debug) # tell OW that we're ready for the next (only) iteration
# 'results.txt' is in the same directory as the *blb file
if os.path.exists(self.resname):
resNewmtime = os.path.getmtime(self.resname)
if resNewmtime > resmtime: # file has changed
if self.debug:
sys.stderr.write('results.txt already updated')
else:
acutils.waitForNotify(watchFile=self.resname, path=self.dname, callback=self.getCBvalue, debug=self.debug)
else:
if self.debug:
sys.stderr.write('OWACComp waiting for {:} (modified positions)\n'.format(self.resname))
acutils.waitForNotify(watchFile=self.resname, path=self.dname, callback=self.getCBvalue, debug=self.debug)
# Parse output file
# Enterprise OW writes the report file specified in the script BUT
# Academic OW writes 'results.txt' (which doesn't have as much information)
netEnergy, netNRGturb, grossNRGturb = acutils.parseACresults(fname=self.resname)
if netEnergy is None:
sys.stderr.write("Error reading results file\n")
if self.debug:
sys.stderr.write('Stopping OpenWind with pid {:}\n'.format(self.pid))
self.proc.terminate()
return False
# Set the output variables
# - array_aep is not available from Academic 'results.txt' file
self.nTurbs = len(netNRGturb)
self.net_aep = netEnergy
self.gross_aep = sum(grossNRGturb)
if self.debug:
sys.stderr.write('{:}\n'.format(self.dump()))
# Log optimization values
if self.opt_log:
self.olfh.write('{:3d} G {:.4f} N {:.4f} XY '.format(self.exec_count, self.gross_aep, self.net_aep))
for ii in range(len(wt_positions)):
self.olfh.write('{:8.1f} {:9.1f} '.format(self.wt_layout.wt_positions[ii][0], self.wt_layout.wt_positions[ii][1]))
self.olfh.write('\n')
if not self.start_once and self.stopOW:
if self.debug:
sys.stderr.write('Stopping OpenWind with pid {:}\n'.format(self.pid))
self.proc.terminate()
self.checkReport() # check for execution errors
if self.debug:
sys.stderr.write(" Leaving {0}.execute() {1}...\n".format(self.__class__, self.script_file))
#------------------
def dump(self):
# returns a string with a summary of object parameters
dumpstr = ''
dumpstr += 'Gross {:10.4f} GWh Net {:10.4f} GWh from {:4d} turbines'.format(
self.gross_aep*0.000001,self.net_aep*0.000001, self.nTurbs)
#print dumpstr
return dumpstr
#------------------
def getCBvalue(self,val):
''' Callback invoked when waitForNotify detects change in results file
Sets self.net_aep to its argument
waitForNotify has handler which reads results.txt and calls this
function with netEnergy
Is this redundant with other parser for results.txt?
'''
self.net_aep = val
#------------------
def terminateOW(self):
''' Terminate the OpenWind process '''
if self.debug:
sys.stderr.write('Stopping OpenWind with pid {:}\n'.format(self.pid))
self.proc.terminate()
#------------------
def checkReport(self):
''' check the report file for errors '''
fname = self.scriptDict['rptpath']
if self.debug:
sys.stderr.write('checkReport : {:}\n'.format(fname))
fh = open(fname, 'r')
for line in fh.readlines():
if line.startswith('Failed to find and replace turbine type'):
sys.stderr.write('\n*** ERROR: turbine replacement operation failed\n')
sys.stderr.write(' Replace {:}\n'.format(self.scriptDict['replturbname']))
sys.stderr.write(' with {:}\n'.format(self.scriptDict['replturbpath']))
sys.stderr.write('\n')
fh.close()
#------------------------------------------------------------------
def dummy_wt_list():
wtl = ExtendedWindTurbinePowerCurveVT()
nv = 20
wtl.hub_height = 100.0
wtl.rotor_diameter = 90.0
wtl.power_rating = 3.0
wtl.rpm_curve = [ [float(i), 10.0] for i in range(nv) ]
wtl.pitch_curve = [ [float(i), 0.0] for i in range(nv) ]
wtl.c_t_curve = [ [float(i), 10.0] for i in range(nv) ]
wtl.power_curve = [ [float(i), 10.0] for i in range(nv) ]
return wtl
#------------------------------------------------------------------
def wtlDump(wtl):
wstr = 'WTL: pclen {:}'.format(len(wtl.c_t_curve))
return wstr
#------------------------------------------------------------------
''' OWACComp.wt_layout is a ExtendedWindFarmTurbineLayout(VariableTree) and has
wt_list = List(ExtendedWindTurbinePowerCurveVT(), desc='The wind turbine list of descriptions [n_wt]')
wt_positions = Array(units='m', desc='Array of wind turbines attached to particular positions [n_wt, 2]')
(among others)
We use wt_positions to move the turbines - we update the values and copy them to
file 'positions.txt' at each iteration using writePositionFile()
(ow.wt_layout.wt_positions and wt_positions are 2 copies of the same data)
If we are replacing the turbines, we use wt_list to hold the modified turbine.
We initialize wt_layout.wt_list with copies of the values in base_turbine_file.
At each iteration, we tweak the values in wt_layout.wt_list.
When OWACComp.execute runs, it writes a new turbine file
using the values in wt_layout.wt_list[0]
This turbine file is the same one specified in the script:
<TurbinePath value="../templates/ReplTurb.owtg"/>
When OpenWind runs the Replace Turbine operation, it looks for all turbines whose name matches
the value in <TurbineName value="NREL 5MW"/> and replaces them with the turbine described in
file <TurbinePath>
Does the base_turbine_file need to match the default turbine in the workbook?
How can we get that name?
- run OW energy capture, scan file
- but scripted energy capture doesn't have full description of turbine
'''
def example(owExe):
debug = False
start_once = False
modify_turbine = False
opt_log = False
for arg in sys.argv[1:]:
if arg == '-debug':
debug = True
if arg == '-once':
start_once = True
if arg == '-log':
opt_log = True
if arg == '-modturb':
modify_turbine = True
if arg == '-help':
sys.stderr.write('USAGE: python openWindAcComponent.py [-once] [-debug]\n')
exit()
# Find OpenWind executable
if not os.path.isfile(owExe):
sys.stderr.write('OpenWind executable file "{:}" not found\n'.format(owExe))
exit()
# set the external optimiser flag to True so that we can use our optimizing routines
acutils.owIniSet(owExe, extVal=True, debug=True)
# Set OpenWind script name
testpath = '../templates/'
#owXMLname = testpath + 'rtecScript.xml' # replace turb, energy capture #KLD - this script does not work for me with this component
owXMLname = testpath + 'owacScript.xml' # optimize operation
#owXMLname = testpath + 'rtopScript.xml' # replace turb, optimize
if modify_turbine:
owXMLname = testpath + 'rtopScript.xml' # replace turb, optimize
if not os.path.isfile(owXMLname):
sys.stderr.write('OpenWind script file "{:}" not found\n'.format(owXMLname))
exit()
dscript = rwScriptXML.rdScript(owXMLname,debug=debug) # Show our operations
workbook = dscript['workbook']
# default turbine positions and size of translation
wt_positions = [[456000.00,4085000.00],
[456500.00,4085000.00]]
deltaX = 3000.0
deltaY = -2000.0
#deltaX = 200.0
#deltaY = -200.0
deltaX = 3.000
deltaY = -2.000
# Read turbine positions from workbook
if debug:
sys.stderr.write('Getting turbine positions from {:}\n'.format(workbook))
wb = acutils.WTWkbkFile(wkbk=workbook, owexe=owExe)
wt_positions = wb.xy
if debug:
sys.stderr.write('Got {:} turbine positions\n'.format(len(wt_positions)))
# Initialize OWACcomp component
ow = OWACcomp(owExe=owExe, debug=debug, scriptFile=owXMLname, start_once=start_once, opt_log=opt_log) #, stopOW=False)
if not ow.scriptOK:
sys.stderr.write("\n*** ERROR found in script file\n\n")
exit()
# starting point for turbine mods
#wt_list_elem = dummy_wt_list()
base_turbine_file = testpath + 'NREL5MW.owtg'
wt_list_elem = turbfuncs.owtg_to_wtpc(base_turbine_file)
ow.wt_layout.wt_list = [ wt_list_elem for i in range(len(wt_positions)) ]
if debug:
sys.stderr.write('Initialized {:} turbines in wt_layout\n'.format(len(wt_positions)))
# With each iteration
# move turbines farther offshore
# possibly modify the turbine rotor diam and power curve and replace turbine
if debug:
ofh = open('wtp.txt', 'w')
for irun in range(1,4):
for i in range(len(wt_positions)):
wt_positions[i][0] += deltaX
wt_positions[i][1] += deltaY
if debug:
ofh.write('{:2d} {:3d} {:.1f} {:.1f}\n'.format(irun, i, wt_positions[i][0], wt_positions[i][1]))
ow.wt_layout.wt_positions = wt_positions
# modify the turbine
ow.rotor_diameter += 1.0
if ow.replace_turbine:
wt_list_elem = ow.wt_layout.wt_list[0]
wt_list_elem.power_rating *= 1.05
for i in range(len(wt_list_elem.power_curve)):
wt_list_elem.power_curve[i][1] *= 1.05
ow.wt_layout.wt_list = [wt_list_elem for i in range(len(ow.wt_layout.wt_list)) ]
if debug:
ofh.write('Updated {:} turbines with:\n'.format(len(ow.wt_layout.wt_list)))
ofh.write(turbfuncs.wtpc_dump(ow.wt_layout.wt_list[0]))
ow.execute() # run the openWind process
print '\nFinal values'
owd = ow.dump()
print ' {:}'.format(owd)
print '-' * 40, '\n'
if start_once:
ow.terminateOW()
if __name__ == "__main__":
# Substitute your own path to Openwind Enterprise
#owExe = 'C:/Models/Openwind/openWind64_ac.exe'
owExe = 'D:/rassess/Openwind/openWind64_ac.exe' # Old Academic v.1275
owExe = 'D:/rassess/Openwind/openWind64.exe'
example(owExe) | 41.979853 | 137 | 0.590899 |
'''
Execute OpenWindAcademic as an OpenMDAO Component
After execute(), the following variables have been updated:
nTurbs
net_aep
gross_aep
They can be accessed through appropriate connections.
NOTE: Script file must contain an Optimize/Optimise operation - otherwise,
no results will be found.
Typical use (e.g., from an Assembly):
owac = OWACcomp(owExe, scriptFile=scrptName, debug=False, stopOW=True, start_once=False, opt_log=False)
main() runs OWACcomp.execute() 3 times, moving and modifying the turbines each time
'''
import os.path
import sys, time
import subprocess
from lxml import etree
import owAcademicUtils as acutils
import plant_energyse.openwind.openWindUtils as utils
import plant_energyse.openwind.rwScriptXML as rwScriptXML
import plant_energyse.openwind.rwTurbXML as rwTurbXML
import plant_energyse.openwind.turbfuncs as turbfuncs
from openmdao.lib.datatypes.api import Float, Int, VarTree
from openmdao.main.api import FileMetadata, Component, VariableTree
from fusedwind.plant_flow.vt import GenericWindTurbineVT, \
GenericWindTurbinePowerCurveVT, ExtendedWindTurbinePowerCurveVT, \
GenericWindFarmTurbineLayout, ExtendedWindFarmTurbineLayout
from fusedwind.interface import implement_base
from fusedwind.plant_flow.comp import BaseAEPAggregator
@implement_base(BaseAEPAggregator)
class OWACcomp(Component):
""" A simple OpenMDAO component for OpenWind academic
Args:
owExe (str): full path to OpenWind executable
scriptFile (str): path to XML script that OpenWind will run
"""
rotor_diameter = Float(126.0, iotype='in', units='m', desc='connecting rotor diameter to force run on change')
availability = Float(0.95, iotype='in', desc='availability')
other_losses = Float(0.0, iotype='in', desc='soiling losses')
wt_layout = VarTree(ExtendedWindFarmTurbineLayout(), iotype='in', desc='properties for each wind turbine and layout')
dummyVbl = Float(0, iotype='in', desc='unused variable to make it easy to do DOE runs')
gross_aep = Float(0.0, iotype='out', desc='Gross Output')
net_aep = Float(0.0, iotype='out', desc='Net Output')
nTurbs = Int(0, iotype='out', desc='Number of turbines')
def __init__(self, owExe, scriptFile=None, debug=False, stopOW=True, start_once=False, opt_log=False):
""" Constructor for the OWACwrapped component """
self.debug = debug
if self.debug:
sys.stderr.write('\nIn {:}.__init__()\n'.format(self.__class__))
super(OWACcomp, self).__init__()
self.input_file = 'myinput.txt'
self.output_file = 'myoutput.txt'
self.stderr = 'myerror.log'
self.external_files = [
FileMetadata(path=self.output_file),
FileMetadata(path=self.stderr),
]
self.stopOW = stopOW
self.start_once = start_once
self.replace_turbine = False
self.opt_log = opt_log
self.resname = ''
self.script_file = scriptFile
self.scriptOK = False
if scriptFile is not None:
self.scriptOK = self.parse_scriptFile()
if not self.scriptOK:
raise ValueError
return
self.scriptDict = rwScriptXML.rdScript(self.script_file, self.debug)
if self.debug:
sys.stderr.write('Script File Contents:\n')
for k in self.scriptDict.keys():
sys.stderr.write(' {:12s} {:}\n'.format(k,self.scriptDict[k]))
if self.opt_log:
self.olname = 'owacOptLog.txt'
self.olfh = open(self.olname, 'w')
if self.debug:
sys.stderr.write('Logging optimization params to {:}\n'.format(self.olname))
self.command = [owExe, self.script_file]
self.rtr_diam_init = self.rotor_diameter
if self.start_once:
self.proc = subprocess.Popen(self.command)
self.pid = self.proc.pid
if self.debug:
sys.stderr.write('Started OpenWind with pid {:}\n'.format(self.pid))
sys.stderr.write(' OWACComp: dummyVbl {:}\n'.format(self.dummyVbl))
if self.debug:
sys.stderr.write('\nLeaving {:}.__init__()\n'.format(self.__class__))
def parse_scriptFile(self):
if not os.path.isfile(self.script_file):
sys.stderr.write('\n*** OpenWind script file "{:}" not found\n'.format(self.script_file))
return False
try:
e = etree.parse(self.script_file)
self.rptpath = e.getroot().find('ReportPath').get('value')
except:
sys.stderr.write("\n*** Can't find ReportPath in {:}\n".format(self.script_file))
self.rptpath = 'NotFound'
return False
# Make sure there's an optimize operation - otherwise OWAC won't find anything
foundOpt = False
self.replace_turbine = False
ops = e.getroot().findall('.//Operation')
for op in ops:
optype = op.find('Type').get('value')
if optype == 'Optimize' or optype == 'Optimise':
foundOpt = True
break
if optype == 'Replace Turbine Type':
self.replace_turbine = True
sys.stderr.write('\n*** WARNING: start_once will be set to False because Replace Turbine\n')
sys.stderr.write(' operation is present in {:}\n\n'.format(self.script_file))
self.start_once = False
if not foundOpt:
sys.stderr.write('\n*** ERROR: no Optimize operation found in {:}\n\n'.format(self.script_file))
return False
if self.replace_turbine and self.start_once:
sys.stderr.write("*** WARNING: can't use start_once when replacing turbine\n")
sys.stderr.write(" setting start_once to False\n")
self.start_once = False
self.dname = None
for op in ops:
if op.find('Type').get('value') == 'Change Workbook':
wkbk = op.find('Path').get('value')
if not os.path.isfile(wkbk):
sys.stderr.write("\n*** OpenWind workbook file {:}\n not found\n".format(wkbk))
sys.stderr.write(" (specified in script file {:})\n".format(self.script_file))
return False
self.dname = os.path.dirname(wkbk)
if self.debug:
sys.stderr.write('Working directory: {:}\n'.format(self.dname))
break
self.resname = '/'.join([self.dname,'results.txt'])
return True
def execute(self):
""" Executes our component. """
if self.debug:
sys.stderr.write(" In {0}.execute() {1}...\n".format(self.__class__, self.script_file))
if (len(self.resname) < 1):
sys.stderr.write('\n*** ERROR: OWAcomp results file name not assigned! (problem with script file?)\n\n')
return False
if self.replace_turbine:
if len(self.wt_layout.wt_list) < 1:
sys.stderr.write('\n*** ERROR *** OWACcomp::execute(): no turbines in wt_layout!\n\n')
return False
if self.debug:
sys.stderr.write('Replacement turbine parameters:\n')
sys.stderr.write('{:}\n'.format(turbfuncs.wtpc_dump(self.wt_layout.wt_list[0], shortFmt=True)))
newXML = turbfuncs.wtpc_to_owtg(self.wt_layout.wt_list[0],
trbname='ReplTurb',
desc='OWACcomp replacement turbine')
if len(newXML) > 50:
tfname = self.scriptDict['replturbpath']
tfh = open(tfname, 'w')
tfh.write(newXML)
tfh.close()
maxPower = self.wt_layout.wt_list[0].power_rating
if self.debug:
sys.stderr.write('Wrote new turbine file to {:} (rated pwr {:.2f} MW\n'.format(tfname, maxPower*0.000001))
else:
sys.stderr.write('*** NO new turbine file written\n')
if not self.start_once:
self.proc = subprocess.Popen(self.command)
self.pid = self.proc.pid
if self.debug:
sys.stderr.write('Started OpenWind with pid {:}\n'.format(self.pid))
sys.stderr.write(' OWACComp: dummyVbl {:}\n'.format(self.dummyVbl))
if self.debug:
sys.stderr.write('OWACComp waiting for {:} (first run - positions unchanged)\n'.format(self.resname))
acutils.waitForNotify(watchFile=self.resname, path=self.dname, debug=False, callback=self.getCBvalue)
acutils.writePositionFile(self.wt_layout.wt_positions, path=self.dname, debug=self.debug)
if os.path.exists(self.resname):
resmtime = os.path.getmtime(self.resname)
if self.debug:
sys.stderr.write('ModTime({:}): {:}\n'.format(self.resname, time.asctime(time.localtime(resmtime))))
else:
if self.debug:
sys.stderr.write('{:} does not exist yet\n'.format(self.resname))
acutils.writeNotify(path=self.dname, debug=self.debug)
# 'results.txt' is in the same directory as the *blb file
if os.path.exists(self.resname):
resNewmtime = os.path.getmtime(self.resname)
if resNewmtime > resmtime: # file has changed
if self.debug:
sys.stderr.write('results.txt already updated')
else:
acutils.waitForNotify(watchFile=self.resname, path=self.dname, callback=self.getCBvalue, debug=self.debug)
else:
if self.debug:
sys.stderr.write('OWACComp waiting for {:} (modified positions)\n'.format(self.resname))
acutils.waitForNotify(watchFile=self.resname, path=self.dname, callback=self.getCBvalue, debug=self.debug)
# Parse output file
# Enterprise OW writes the report file specified in the script BUT
# Academic OW writes 'results.txt' (which doesn't have as much information)
netEnergy, netNRGturb, grossNRGturb = acutils.parseACresults(fname=self.resname)
if netEnergy is None:
sys.stderr.write("Error reading results file\n")
if self.debug:
sys.stderr.write('Stopping OpenWind with pid {:}\n'.format(self.pid))
self.proc.terminate()
return False
self.nTurbs = len(netNRGturb)
self.net_aep = netEnergy
self.gross_aep = sum(grossNRGturb)
if self.debug:
sys.stderr.write('{:}\n'.format(self.dump()))
if self.opt_log:
self.olfh.write('{:3d} G {:.4f} N {:.4f} XY '.format(self.exec_count, self.gross_aep, self.net_aep))
for ii in range(len(wt_positions)):
self.olfh.write('{:8.1f} {:9.1f} '.format(self.wt_layout.wt_positions[ii][0], self.wt_layout.wt_positions[ii][1]))
self.olfh.write('\n')
if not self.start_once and self.stopOW:
if self.debug:
sys.stderr.write('Stopping OpenWind with pid {:}\n'.format(self.pid))
self.proc.terminate()
self.checkReport()
if self.debug:
sys.stderr.write(" Leaving {0}.execute() {1}...\n".format(self.__class__, self.script_file))
def dump(self):
dumpstr = ''
dumpstr += 'Gross {:10.4f} GWh Net {:10.4f} GWh from {:4d} turbines'.format(
self.gross_aep*0.000001,self.net_aep*0.000001, self.nTurbs)
return dumpstr
def getCBvalue(self,val):
''' Callback invoked when waitForNotify detects change in results file
Sets self.net_aep to its argument
waitForNotify has handler which reads results.txt and calls this
function with netEnergy
Is this redundant with other parser for results.txt?
'''
self.net_aep = val
def terminateOW(self):
''' Terminate the OpenWind process '''
if self.debug:
sys.stderr.write('Stopping OpenWind with pid {:}\n'.format(self.pid))
self.proc.terminate()
def checkReport(self):
''' check the report file for errors '''
fname = self.scriptDict['rptpath']
if self.debug:
sys.stderr.write('checkReport : {:}\n'.format(fname))
fh = open(fname, 'r')
for line in fh.readlines():
if line.startswith('Failed to find and replace turbine type'):
sys.stderr.write('\n*** ERROR: turbine replacement operation failed\n')
sys.stderr.write(' Replace {:}\n'.format(self.scriptDict['replturbname']))
sys.stderr.write(' with {:}\n'.format(self.scriptDict['replturbpath']))
sys.stderr.write('\n')
fh.close()
def dummy_wt_list():
wtl = ExtendedWindTurbinePowerCurveVT()
nv = 20
wtl.hub_height = 100.0
wtl.rotor_diameter = 90.0
wtl.power_rating = 3.0
wtl.rpm_curve = [ [float(i), 10.0] for i in range(nv) ]
wtl.pitch_curve = [ [float(i), 0.0] for i in range(nv) ]
wtl.c_t_curve = [ [float(i), 10.0] for i in range(nv) ]
wtl.power_curve = [ [float(i), 10.0] for i in range(nv) ]
return wtl
def wtlDump(wtl):
wstr = 'WTL: pclen {:}'.format(len(wtl.c_t_curve))
return wstr
''' OWACComp.wt_layout is a ExtendedWindFarmTurbineLayout(VariableTree) and has
wt_list = List(ExtendedWindTurbinePowerCurveVT(), desc='The wind turbine list of descriptions [n_wt]')
wt_positions = Array(units='m', desc='Array of wind turbines attached to particular positions [n_wt, 2]')
(among others)
We use wt_positions to move the turbines - we update the values and copy them to
file 'positions.txt' at each iteration using writePositionFile()
(ow.wt_layout.wt_positions and wt_positions are 2 copies of the same data)
If we are replacing the turbines, we use wt_list to hold the modified turbine.
We initialize wt_layout.wt_list with copies of the values in base_turbine_file.
At each iteration, we tweak the values in wt_layout.wt_list.
When OWACComp.execute runs, it writes a new turbine file
using the values in wt_layout.wt_list[0]
This turbine file is the same one specified in the script:
<TurbinePath value="../templates/ReplTurb.owtg"/>
When OpenWind runs the Replace Turbine operation, it looks for all turbines whose name matches
the value in <TurbineName value="NREL 5MW"/> and replaces them with the turbine described in
file <TurbinePath>
Does the base_turbine_file need to match the default turbine in the workbook?
How can we get that name?
- run OW energy capture, scan file
- but scripted energy capture doesn't have full description of turbine
'''
def example(owExe):
debug = False
start_once = False
modify_turbine = False
opt_log = False
for arg in sys.argv[1:]:
if arg == '-debug':
debug = True
if arg == '-once':
start_once = True
if arg == '-log':
opt_log = True
if arg == '-modturb':
modify_turbine = True
if arg == '-help':
sys.stderr.write('USAGE: python openWindAcComponent.py [-once] [-debug]\n')
exit()
# Find OpenWind executable
if not os.path.isfile(owExe):
sys.stderr.write('OpenWind executable file "{:}" not found\n'.format(owExe))
exit()
# set the external optimiser flag to True so that we can use our optimizing routines
acutils.owIniSet(owExe, extVal=True, debug=True)
# Set OpenWind script name
testpath = '../templates/'
#owXMLname = testpath + 'rtecScript.xml' # replace turb, energy capture #KLD - this script does not work for me with this component
owXMLname = testpath + 'owacScript.xml' # optimize operation
#owXMLname = testpath + 'rtopScript.xml' # replace turb, optimize
if modify_turbine:
owXMLname = testpath + 'rtopScript.xml' # replace turb, optimize
if not os.path.isfile(owXMLname):
sys.stderr.write('OpenWind script file "{:}" not found\n'.format(owXMLname))
exit()
dscript = rwScriptXML.rdScript(owXMLname,debug=debug) # Show our operations
workbook = dscript['workbook']
# default turbine positions and size of translation
wt_positions = [[456000.00,4085000.00],
[456500.00,4085000.00]]
deltaX = 3000.0
deltaY = -2000.0
#deltaX = 200.0
#deltaY = -200.0
deltaX = 3.000
deltaY = -2.000
# Read turbine positions from workbook
if debug:
sys.stderr.write('Getting turbine positions from {:}\n'.format(workbook))
wb = acutils.WTWkbkFile(wkbk=workbook, owexe=owExe)
wt_positions = wb.xy
if debug:
sys.stderr.write('Got {:} turbine positions\n'.format(len(wt_positions)))
# Initialize OWACcomp component
ow = OWACcomp(owExe=owExe, debug=debug, scriptFile=owXMLname, start_once=start_once, opt_log=opt_log) #, stopOW=False)
if not ow.scriptOK:
sys.stderr.write("\n*** ERROR found in script file\n\n")
exit()
# starting point for turbine mods
#wt_list_elem = dummy_wt_list()
base_turbine_file = testpath + 'NREL5MW.owtg'
wt_list_elem = turbfuncs.owtg_to_wtpc(base_turbine_file)
ow.wt_layout.wt_list = [ wt_list_elem for i in range(len(wt_positions)) ]
if debug:
sys.stderr.write('Initialized {:} turbines in wt_layout\n'.format(len(wt_positions)))
# With each iteration
# move turbines farther offshore
# possibly modify the turbine rotor diam and power curve and replace turbine
if debug:
ofh = open('wtp.txt', 'w')
for irun in range(1,4):
for i in range(len(wt_positions)):
wt_positions[i][0] += deltaX
wt_positions[i][1] += deltaY
if debug:
ofh.write('{:2d} {:3d} {:.1f} {:.1f}\n'.format(irun, i, wt_positions[i][0], wt_positions[i][1]))
ow.wt_layout.wt_positions = wt_positions
# modify the turbine
ow.rotor_diameter += 1.0
if ow.replace_turbine:
wt_list_elem = ow.wt_layout.wt_list[0]
wt_list_elem.power_rating *= 1.05
for i in range(len(wt_list_elem.power_curve)):
wt_list_elem.power_curve[i][1] *= 1.05
ow.wt_layout.wt_list = [wt_list_elem for i in range(len(ow.wt_layout.wt_list)) ]
if debug:
ofh.write('Updated {:} turbines with:\n'.format(len(ow.wt_layout.wt_list)))
ofh.write(turbfuncs.wtpc_dump(ow.wt_layout.wt_list[0]))
ow.execute() # run the openWind process
print '\nFinal values'
owd = ow.dump()
print ' {:}'.format(owd)
print '-' * 40, '\n'
if start_once:
ow.terminateOW()
if __name__ == "__main__":
# Substitute your own path to Openwind Enterprise
#owExe = 'C:/Models/Openwind/openWind64_ac.exe'
owExe = 'D:/rassess/Openwind/openWind64_ac.exe' # Old Academic v.1275
owExe = 'D:/rassess/Openwind/openWind64.exe'
example(owExe) | false | true |
f72c464b80241ef5e87521b090940d0e329fe244 | 2,462 | py | Python | algotrader/trading/context.py | alexcwyu/python-trading | a494f602411a3ebfdecae002a16a5ea93fc7a046 | [
"Apache-2.0"
] | 17 | 2016-03-30T21:52:30.000Z | 2021-05-01T18:21:48.000Z | algotrader/trading/context.py | ajmal017/python-trading | a494f602411a3ebfdecae002a16a5ea93fc7a046 | [
"Apache-2.0"
] | 2 | 2016-10-04T19:29:05.000Z | 2017-02-01T19:24:39.000Z | algotrader/trading/context.py | ajmal017/python-trading | a494f602411a3ebfdecae002a16a5ea93fc7a046 | [
"Apache-2.0"
] | 9 | 2016-04-24T05:05:26.000Z | 2020-05-03T13:01:34.000Z | from algotrader import Context
from algotrader.model.model_factory import ModelFactory
from algotrader.provider import ProviderManager
from algotrader.provider.broker import Broker
from algotrader.provider.datastore import DataStore
from algotrader.provider.feed import Feed
from algotrader.strategy import StrategyManager
from algotrader.trading.account import AccountManager
from algotrader.trading.clock import Clock, RealTimeClock, SimulationClock
from algotrader.trading.config import Config
from algotrader.trading.event import EventBus
from algotrader.trading.instrument_data import InstrumentDataManager
from algotrader.trading.order import OrderManager
from algotrader.trading.portfolio import Portfolio, PortfolioManager
from algotrader.trading.ref_data import RefDataManager
from algotrader.trading.sequence import SequenceManager
class ApplicationContext(Context):
def __init__(self, config: Config = None):
super(ApplicationContext, self).__init__()
self.config = config if config else Config()
self.clock = self.add_startable(self.__get_clock())
self.provider_mgr = self.add_startable(ProviderManager())
self.seq_mgr = self.add_startable(SequenceManager())
self.inst_data_mgr = self.add_startable(InstrumentDataManager())
self.ref_data_mgr = self.add_startable(RefDataManager())
self.order_mgr = self.add_startable(OrderManager())
self.acct_mgr = self.add_startable(AccountManager())
self.portf_mgr = self.add_startable(PortfolioManager())
self.stg_mgr = self.add_startable(StrategyManager())
self.event_bus = EventBus()
self.model_factory = ModelFactory
def __get_clock(self) -> Clock:
if self.config.get_app_config("clockId", Clock.Simulation) == Clock.RealTime:
return RealTimeClock()
return SimulationClock()
def get_data_store(self) -> DataStore:
return self.provider_mgr.get(self.config.get_app_config("dataStoreId"))
def get_broker(self) -> Broker:
return self.provider_mgr.get(self.config.get_app_config("brokerId"))
def get_feed(self) -> Feed:
return self.provider_mgr.get(self.config.get_app_config("feedId"))
def get_portfolio(self) -> Portfolio:
return self.portf_mgr.get_or_new_portfolio(self.config.get_app_config("dataStoreId"),
self.config.get_app_config("portfolioInitialcash"))
| 42.448276 | 102 | 0.750203 | from algotrader import Context
from algotrader.model.model_factory import ModelFactory
from algotrader.provider import ProviderManager
from algotrader.provider.broker import Broker
from algotrader.provider.datastore import DataStore
from algotrader.provider.feed import Feed
from algotrader.strategy import StrategyManager
from algotrader.trading.account import AccountManager
from algotrader.trading.clock import Clock, RealTimeClock, SimulationClock
from algotrader.trading.config import Config
from algotrader.trading.event import EventBus
from algotrader.trading.instrument_data import InstrumentDataManager
from algotrader.trading.order import OrderManager
from algotrader.trading.portfolio import Portfolio, PortfolioManager
from algotrader.trading.ref_data import RefDataManager
from algotrader.trading.sequence import SequenceManager
class ApplicationContext(Context):
def __init__(self, config: Config = None):
super(ApplicationContext, self).__init__()
self.config = config if config else Config()
self.clock = self.add_startable(self.__get_clock())
self.provider_mgr = self.add_startable(ProviderManager())
self.seq_mgr = self.add_startable(SequenceManager())
self.inst_data_mgr = self.add_startable(InstrumentDataManager())
self.ref_data_mgr = self.add_startable(RefDataManager())
self.order_mgr = self.add_startable(OrderManager())
self.acct_mgr = self.add_startable(AccountManager())
self.portf_mgr = self.add_startable(PortfolioManager())
self.stg_mgr = self.add_startable(StrategyManager())
self.event_bus = EventBus()
self.model_factory = ModelFactory
def __get_clock(self) -> Clock:
if self.config.get_app_config("clockId", Clock.Simulation) == Clock.RealTime:
return RealTimeClock()
return SimulationClock()
def get_data_store(self) -> DataStore:
return self.provider_mgr.get(self.config.get_app_config("dataStoreId"))
def get_broker(self) -> Broker:
return self.provider_mgr.get(self.config.get_app_config("brokerId"))
def get_feed(self) -> Feed:
return self.provider_mgr.get(self.config.get_app_config("feedId"))
def get_portfolio(self) -> Portfolio:
return self.portf_mgr.get_or_new_portfolio(self.config.get_app_config("dataStoreId"),
self.config.get_app_config("portfolioInitialcash"))
| true | true |
f72c464dc5c8ee869e61bd1a0fbcf6cc63feb838 | 3,082 | py | Python | lispy/lisp.py | fucangyu/myself-impls | 9fd2730f9e0e12f95559d2f4e41c34b670441428 | [
"MIT"
] | 3 | 2019-01-04T12:54:16.000Z | 2019-01-13T07:08:10.000Z | lispy/lisp.py | fucangyu/myself-impls | 9fd2730f9e0e12f95559d2f4e41c34b670441428 | [
"MIT"
] | null | null | null | lispy/lisp.py | fucangyu/myself-impls | 9fd2730f9e0e12f95559d2f4e41c34b670441428 | [
"MIT"
] | 1 | 2019-08-27T18:29:53.000Z | 2019-08-27T18:29:53.000Z | import math
import operator as op
from collections import ChainMap as Environment
Symbol = str
List = list
Number = (int, float)
def parse(program: str):
return read_from_tokens(tokenize(program))
def tokenize(raw):
return raw.replace('(', ' ( ').replace(')', ' ) ').split()
def read_from_tokens(tokens: list):
if not len(tokens):
raise SyntaxError('unexpected EOF')
head = tokens.pop(0)
if head == '(':
L = []
while tokens[0] != ')':
L.append(read_from_tokens(tokens))
tokens.pop(0)
return L
elif head == ')':
raise SyntaxError('unexpected )')
else:
return atom(head)
def atom(token: str) -> 'Atom':
try:
return int(token)
except ValueError:
try:
return float(token)
except ValueError:
return Symbol(token)
def gen_env() -> dict:
env = {}
env.update(vars(math))
env.update({
'+': op.add,
'-': op.sub,
'*': op.mul,
'/': op.truediv,
'>': op.gt,
'<': op.lt,
'>=': op.ge,
'<=': op.le,
'=': op.eq,
'abs': abs,
'append': op.add,
'apply': lambda proc, args: proc(*args),
'begin': lambda *x: x[-1],
'car': lambda x: x[0],
'cdr': lambda x: x[1:],
'cons': lambda x, y: [x] + y,
'eq?': op.is_,
'equal?': op.eq,
'length': len,
'list': lambda *x: list(x),
'list?': lambda x: isinstance(x, list),
'map': lambda *args: list(map(*args)),
'max': max,
'min': min,
'not': op.not_,
'null?': lambda x: x == [],
'number?': lambda x: isinstance(x, Number),
'procedure?': callable,
'round': round,
'symbol?': lambda x: isinstance(x, Symbol),
})
return env
global_env = gen_env()
def eval(x, env=global_env):
if isinstance(x, Symbol):
return env[x]
elif isinstance(x, Number):
return x
elif x[0] == 'quote':
_, exp = x
return exp
elif x[0] == 'if':
_, test, conseq, alt = x
exp = (conseq if eval(test, env) else alt)
return eval(exp, env)
elif x[0] == 'define':
_, symbol, exp = x
env[symbol] = eval(exp, env)
elif x[0] == 'lambda':
_, parms, body = x
return Procedure(parms, body, env)
else:
proc = eval(x[0], env)
args = [eval(arg, env) for arg in x[1:]]
return proc(*args)
def repl(prompt='lispy>> '):
while True:
val = eval(parse(input(prompt)))
if val is not None:
print(schemestr(val))
def schemestr(exp):
if isinstance(exp, List):
return '(' + ' '.join(map(schemestr, exp)) + ')'
else:
return str(exp)
class Procedure(object):
def __init__(self, parms, body, env):
self.parms, self.body, self.env = parms, body, env
def __call__(self, *args):
env = Environment(dict(zip(self.parms, args)), self.env)
return eval(self.body, env)
repl()
| 23.172932 | 64 | 0.508436 | import math
import operator as op
from collections import ChainMap as Environment
Symbol = str
List = list
Number = (int, float)
def parse(program: str):
return read_from_tokens(tokenize(program))
def tokenize(raw):
return raw.replace('(', ' ( ').replace(')', ' ) ').split()
def read_from_tokens(tokens: list):
if not len(tokens):
raise SyntaxError('unexpected EOF')
head = tokens.pop(0)
if head == '(':
L = []
while tokens[0] != ')':
L.append(read_from_tokens(tokens))
tokens.pop(0)
return L
elif head == ')':
raise SyntaxError('unexpected )')
else:
return atom(head)
def atom(token: str) -> 'Atom':
try:
return int(token)
except ValueError:
try:
return float(token)
except ValueError:
return Symbol(token)
def gen_env() -> dict:
env = {}
env.update(vars(math))
env.update({
'+': op.add,
'-': op.sub,
'*': op.mul,
'/': op.truediv,
'>': op.gt,
'<': op.lt,
'>=': op.ge,
'<=': op.le,
'=': op.eq,
'abs': abs,
'append': op.add,
'apply': lambda proc, args: proc(*args),
'begin': lambda *x: x[-1],
'car': lambda x: x[0],
'cdr': lambda x: x[1:],
'cons': lambda x, y: [x] + y,
'eq?': op.is_,
'equal?': op.eq,
'length': len,
'list': lambda *x: list(x),
'list?': lambda x: isinstance(x, list),
'map': lambda *args: list(map(*args)),
'max': max,
'min': min,
'not': op.not_,
'null?': lambda x: x == [],
'number?': lambda x: isinstance(x, Number),
'procedure?': callable,
'round': round,
'symbol?': lambda x: isinstance(x, Symbol),
})
return env
global_env = gen_env()
def eval(x, env=global_env):
if isinstance(x, Symbol):
return env[x]
elif isinstance(x, Number):
return x
elif x[0] == 'quote':
_, exp = x
return exp
elif x[0] == 'if':
_, test, conseq, alt = x
exp = (conseq if eval(test, env) else alt)
return eval(exp, env)
elif x[0] == 'define':
_, symbol, exp = x
env[symbol] = eval(exp, env)
elif x[0] == 'lambda':
_, parms, body = x
return Procedure(parms, body, env)
else:
proc = eval(x[0], env)
args = [eval(arg, env) for arg in x[1:]]
return proc(*args)
def repl(prompt='lispy>> '):
while True:
val = eval(parse(input(prompt)))
if val is not None:
print(schemestr(val))
def schemestr(exp):
if isinstance(exp, List):
return '(' + ' '.join(map(schemestr, exp)) + ')'
else:
return str(exp)
class Procedure(object):
def __init__(self, parms, body, env):
self.parms, self.body, self.env = parms, body, env
def __call__(self, *args):
env = Environment(dict(zip(self.parms, args)), self.env)
return eval(self.body, env)
repl()
| true | true |
f72c46adb32a8a5bb98d87da7bfcaf092e3eb79b | 19,109 | py | Python | logs/management/commands/import_log.py | ahemery/ezreports | 9ff0f472ff0f0efd06c8315b99084bd723b0e2f9 | [
"Apache-2.0"
] | null | null | null | logs/management/commands/import_log.py | ahemery/ezreports | 9ff0f472ff0f0efd06c8315b99084bd723b0e2f9 | [
"Apache-2.0"
] | null | null | null | logs/management/commands/import_log.py | ahemery/ezreports | 9ff0f472ff0f0efd06c8315b99084bd723b0e2f9 | [
"Apache-2.0"
] | null | null | null | import csv
import glob
import os
import pycurl
import re
import ldap3
from datetime import date, timedelta, datetime
from dateutil.parser import parse
from django.core.management.base import BaseCommand, CommandError
from django.db import connection
from django.db.models import Max
from django.utils.text import slugify
from front.models import *
config = {
"ldap": {
"server": "ldap.univ-pau.fr",
"user": "cn=consultplus,ou=admin,dc=univ-pau,dc=fr",
"pwd": "uppaplus",
"base": "ou=people,dc=univ-pau,dc=fr"
},
"ezpaarse": {
"server": "http://ezpaarse.univ-pau.fr",
"options": [
"geoip: none",
"Output-Fields: +datetime",
"Crypted-Fields: none"
],
"debug": "false"
},
"logpath": "/mnt/data/dev/scd/ezreports/proxy_logs/*.log",
"csvpath": "/mnt/data/dev/scd/ezreports/csv/",
}
def querylaboratoire(ldap, name):
name = name.replace("\\", "\\5C")
name = name.replace("*", "\2A")
name = name.replace("(", "\\28")
name = name.replace(")", "\\29")
name = name.replace("\0", "\\00")
if not ldap.search(
'ou=structures,dc=univ-pau,dc=fr',
"(ou=" + name + ")",
attributes=['supannCodeEntite']):
return None
return ldap.entries[0].supannCodeEntite.value
def connexions2sql(filename, sql):
"""
Récupère les connexions à partir du fichier de log d'ezproxy
et les stocke en base
:param filename Nom du fichier à traiter
:param sql Cursor sql
:return:
"""
# Expression régulière pour les log d'ezproxy
regex = "^(?P<ip>(?:[0-9]{1,3}\.){3}[0-9]{1,3}) - " \
"(?P<login>[0-9a-zA-Z]*) .*" \
"\[(?P<datetime>.*)\].*connect\?session=.*&url=" \
"https?://w*\.?(?P<url>.[^/]*)/(?P<path>.*) HTTP/1.1.*"
login = re.compile(regex)
# Ouvre le fichier
with open(filename) as file:
# Pour chaque lignes
for line in file:
# Ca match ?
match = login.match(line)
if not match:
continue
url = match.group("url")
date = datetime.strptime(match.group("datetime"), '%d/%b/%Y:%H:%M:%S %z')
# Insertion du lien si inconnu
sql.execute(
"INSERT INTO liens (url, slug, disabled) "
"SELECT %(url)s, %(slug)s, 0 "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM liens WHERE url = %(url)s or slug=%(slug)s) LIMIT 1 ",
params={'url': url, 'slug': slugify(url)})
# Insertion de l'utilisateur si inconnu
sql.execute(
"INSERT INTO utilisateurs (hash) SELECT md5(%(login)s) "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM utilisateurs WHERE hash = md5(%(login)s)) LIMIT 1 ",
params={'login': match.group("login")})
# Insertion de la connexion
sql.execute(
"INSERT INTO connexions "
"SELECT NULL as id, %(date)s as date, %(time)s as time, md5(%(ip)s) as ip, "
"l.id as lien_id, u.id as utilisateur_id "
"FROM utilisateurs u "
"LEFT JOIN liens l on l.url = %(url)s "
"WHERE u.hash = md5(%(login)s) "
"AND NOT EXISTS (SELECT utilisateur_id FROM connexions WHERE "
"utilisateur_id = u.id AND lien_id = l.id AND date = %(date)s "
"AND time = %(time)s AND ip = md5(%(ip)s))",
params={'login': match.group("login"), 'url': url,
'date': date.strftime("%Y-%m-%d"), 'time': date.strftime("%H:%M:%S"),
'ip': match.group("ip")})
connection.commit()
def log2csv(filename):
"""
Converti un fichier log en csv en l'envoyant à ezPAARSE
:param filename: Nom du fichier de log brut
:param outputpath: chemin de sortie du fichier
:return: Nom complet (chemin + nom_du_fichier) du fichier produit
"""
ez = config['ezpaarse']
now = datetime.now()
print(str(now) + " Log 2 CSV : \"" + filename + "\"...")
# Extrait le nom du fichier et son chemin d'accès
path, file = os.path.split(filename)
# Nom du fichier de sortie
outfile = config['csvpath'] + os.path.splitext(file)[0] + '.csv'
return outfile
# On envoie le fichier de log à ezPAARSE
with open(outfile, "wb") as handle:
c = pycurl.Curl()
if ez['debug'] == "true":
c.setopt(c.VERBOSE, 1)
if ez['options'] is not None:
c.setopt(c.HTTPHEADER, ez['options'])
c.setopt(c.URL, ez["server"])
c.setopt(c.HTTPPOST, [(filename, (c.FORM_FILE, filename))])
c.setopt(c.WRITEDATA, handle)
c.perform()
c.close()
return outfile
def csv2sql(filename, sql):
"""
Importe les fichiers CSV produits par ezPAARSE dans une base SQL
:param filename: Nom du fichier CSV à importer
:param sql Connexion sql
:return: Rien
"""
# now = datetime.now()
print(str(datetime.now()) + " CSV 2 SQL : \"" + filename + "\"")
# Ouvre le fichier csv en lecture
with open(filename, 'r') as csvfile:
#
# Connexion à l'annuaire LDAP
server = ldap3.Server(config['ldap']['server'])
ldap = ldap3.Connection(server,
user=config['ldap']['user'],
password=config['ldap']['pwd'],
auto_bind=True)
# Converti le fichier en format CSV
for row in csv.DictReader(csvfile, delimiter=';'):
#print(row)
csvhash = ""
for k, v in sorted(row.items()):
csvhash += v
# Variables
dt = parse(row["datetime"])
login = row["login"]
# Insertion des clefs étrangères
sql.execute("INSERT IGNORE INTO utilisateurs (hash) SELECT md5(%(login)s) "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM utilisateurs WHERE hash = md5(%(login)s))",
params={'login': login})
if row['publisher_name']:
sql.execute("INSERT INTO editeurs (libelle, slug) SELECT %(libelle)s, %(slug)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM editeurs WHERE slug = %(slug)s) LIMIT 1 ",
params={'libelle': row["publisher_name"], 'slug': slugify(row['publisher_name'])})
# todo: Faire le lien entre la ressource et l'éditeur lors de la création d'une nouvelle ressource
if row['platform_name']:
sql.execute("INSERT INTO ressources (libelle, slug) SELECT %(libelle)s, %(slug)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM ressources WHERE slug = %(slug)s) LIMIT 1 ",
params={'slug': slugify(row["platform_name"]), 'libelle': row["platform_name"]})
if row['rtype']:
sql.execute("INSERT INTO types (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM types WHERE code = %(code)s) LIMIT 1 ",
params={'code': row["rtype"]})
if row['mime']:
sql.execute("INSERT INTO formats (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM formats WHERE code = %(code)s) LIMIT 1 ",
params={'code': row["mime"]})
# Insertions des consultations
sql.execute("INSERT INTO consultations "
"(JOUR, HEURE, UTILISATEUR_ID, RESSOURCE_ID, EDITEUR_ID, TYPE_ID, FORMAT_ID, HOST, HASH) "
"SELECT %(jour)s, %(heure)s, u.id, r.id, e.id, t.id, f.id, %(host)s, sha1(%(hash)s) "
"FROM (SELECT 1) as tmp "
"LEFT JOIN utilisateurs u on u.hash = md5(%(login)s) "
"LEFT JOIN ressources r on r.slug = %(ressource)s "
"LEFT JOIN formats f on f.code = %(format)s "
"LEFT JOIN types t on t.code = %(type)s "
"LEFT JOIN editeurs e on e.slug = %(editeur)s "
"WHERE NOT EXISTS(SELECT id FROM consultations WHERE hash = sha1(%(hash)s)) "
"LIMIT 1 ",
{
'jour': dt.date(),
'heure': dt.time(),
'login': login,
'ressource': slugify(row["platform_name"]),
'editeur': slugify(row["publisher_name"]),
'type': row["rtype"],
'format': row["mime"],
'host': row["host"],
'hash': csvhash,
})
ec_id = sql.lastrowid
# On a déjà inséré cette ligne, donc on passe à la suivante
if ec_id == 0:
continue
#
# On récupère les informations LDAP du compte utilisateur
if not ldap.search(
'ou=people,dc=univ-pau,dc=fr',
"(uid=" + login + ")",
attributes=['supannEtuInscription', 'supannEntiteAffectationPrincipale', 'uppaCodeComp',
'uppaDrhComposante', 'uppaProfil', 'uppaDrhLaboratoire']):
print("No ldap informations for \"" + login + "\"")
continue
# todo: Vilain hack, bouuh !
infos = ldap.entries[0]._attributes
if not infos:
continue
#
# Converti le profil en tableau si ce n'est pas le cas
profils = infos["uppaProfil"].values if "uppaProfil" in infos else ["VIDE"]
for profil in profils:
composante_libelle = None
composante_code = None
laboratoire = None
laboratoire_code = None
diplome_libelle = None
diplome_code = None
cursus_annee = None
if profil == "VIDE":
composante_code = infos["uppaCodeComp"]
composante_libelle = infos["uppaDrhComposante"]
#
# Profil étudiant
elif profil in ("ETU", "AE0", "AE1", "AE2", "AET", "AEP"):
if "supannEtuInscription" in infos:
# Eclate le champ supannEtuInscription
inscriptions = infos["supannEtuInscription"].values
for insc in inscriptions:
insc = insc.replace("[", "").split("]")
for d in insc:
d = d.split("=")
if d[0] == "cursusann":
cursus_annee = d[1].replace("{SUPANN}", "")
if d[0] == "libDiplome":
diplome_libelle = d[1]
if d[0] == "diplome":
diplome_code = d[1].replace("{SISE}", "")
else:
cursus_annee = ""
diplome_libelle = infos["uppaDrhComposante"] if "uppaDrhComposante" in infos else None
if isinstance(diplome_libelle, list):
diplome_libelle = diplome_libelle[0]
diplome_code = infos["uppaCodeComp"] if "uppaCodeComp" in infos else None
if isinstance(diplome_code, list):
diplome_code = diplome_code[0]
#
# Profil personnel
elif profil in ("PER", "DOC", "VAC", "INV", "APE", "HEB", "ANC", "APH", "CET", "EME", "LEC",
"PVA", "PAD", "PEC", "STA", "ADM", "AP0", "PAR", "PPE", "ADC", "RSS", "AD0"):
#
# Composante
if "supannEntiteAffectationPrincipale" in infos:
composante_code = infos["supannEntiteAffectationPrincipale"].value
if len(infos["uppaCodeComp"]) > 1:
for id, code in enumerate(infos["uppaCodeComp"]):
if code == composante_code:
composante_libelle = infos["uppaDrhComposante"][id]
break
else:
composante_libelle = infos["uppaDrhComposante"].value
else:
composante_code = infos["uppaCodeComp"].value if "uppaCodeComp" in infos else ""
composante_libelle = infos["uppaDrhComposante"].value if "uppaDrhComposante" in infos else ""
#
# Laboratoire
if "uppaDrhLaboratoire" in infos:
laboratoire = infos["uppaDrhLaboratoire"][0].value \
if isinstance(infos["uppaDrhLaboratoire"], list) else infos["uppaDrhLaboratoire"].value
# todo: Par défaut, prend le premier enregistrement
if isinstance(laboratoire, list):
laboratoire = laboratoire[0]
laboratoire_code = querylaboratoire(ldap, laboratoire)
else:
#print("Profil non géré : " + profil)
continue
#
# Insère les données manquants
sql.execute("INSERT INTO profils (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM profils WHERE code = %(code)s) LIMIT 1 ",
params={'code': profil})
if composante_code is not None and composante_code != 0 \
and composante_libelle is not None and composante_libelle != "":
sql.execute("INSERT INTO composantes (code, libelle) "
"SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT code FROM composantes WHERE code = %(code)s) LIMIT 1 ",
{'code': composante_code, 'libelle': composante_libelle})
# todo: Gérer le cas il y a plusieurs diplomes
if diplome_code is not None and diplome_libelle is not None:
sql.execute("REPLACE INTO diplomes (code, libelle) SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM diplomes WHERE code = %(code)s) LIMIT 1 ",
{'code': diplome_code, 'libelle': diplome_libelle})
if cursus_annee != "" and cursus_annee is not None:
sql.execute("INSERT INTO cursus (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM cursus WHERE code = %(code)s) LIMIT 1 ",
params={'code': cursus_annee})
if laboratoire != "" and laboratoire is not None:
sql.execute("INSERT INTO laboratoires (code, libelle) SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM laboratoires WHERE code = %(code)s "
"or libelle = %(libelle)s) LIMIT 1 ",
params={'code': laboratoire_code, 'libelle': laboratoire})
sql.execute("INSERT IGNORE INTO meta "
"(consultation_id, profil_id, composante_id, laboratoire_id, diplome_id, cursus_id) "
"SELECT %(consultation)s, p.id, co.id, l.id, d.id, c.id "
"FROM profils p "
"LEFT JOIN laboratoires l on l.libelle = %(laboratoire)s "
"LEFT JOIN diplomes d on d.code = %(diplome)s "
"LEFT JOIN cursus c on c.code = %(cursus)s "
"LEFT JOIN composantes co on co.id = %(composante)s "
"WHERE p.code = %(profil)s",
{
'consultation': ec_id,
'profil': profil,
'composante': composante_code,
'laboratoire': laboratoire,
'diplome': diplome_code,
'cursus': cursus_annee
})
connection.commit()
class Command(BaseCommand):
args = '<team_id>'
help = 'Process raw logs from the reverse proxy and import them in database'
def add_arguments(self, parser):
parser.add_argument('--min-date',
help="Everything before this date is ignored (dd/mm/yyyy)",
#default=date.today() - timedelta(1),
required=False)
def handle(self, *args, **options):
# Si aucun argument, on prend depuis la dernière date en base
if not options['min_date']:
#
# Date du dernier fichier traité
query = Connexion.objects.all().aggregate(Max('date'))
mindate = datetime(query['date__max'].year, query['date__max'].month, query['date__max'].day - 1)
else:
try:
mindate = datetime.strptime(options['min_date'], '%d/%m/%Y',)
except ValueError:
raise CommandError('Invalide min-date format !')
# Connexion SQL
sql = connection.cursor()
# Pour chaque fichier de log à traiter
for logfile in sorted(glob.glob(config['logpath'])):
# format du fichier 'ezproxy-YYYY.MM.DD.log'
filename = os.path.split(logfile)[1]
filedate = datetime.strptime(filename, 'ezproxy-%Y.%m.%d.log')
if filedate < mindate:
continue
self.stdout.write("Processing '{}'".format(os.path.basename(logfile)))
#
# Importe les connexions
#
connexions2sql(logfile, sql)
#
# Envoie les données au serveur EZPaarse
#
csvfile = log2csv(logfile)
#
# Envoie les données d'EZPaarse en base sql
#
csv2sql(csvfile, sql)
| 41.905702 | 117 | 0.487676 | import csv
import glob
import os
import pycurl
import re
import ldap3
from datetime import date, timedelta, datetime
from dateutil.parser import parse
from django.core.management.base import BaseCommand, CommandError
from django.db import connection
from django.db.models import Max
from django.utils.text import slugify
from front.models import *
config = {
"ldap": {
"server": "ldap.univ-pau.fr",
"user": "cn=consultplus,ou=admin,dc=univ-pau,dc=fr",
"pwd": "uppaplus",
"base": "ou=people,dc=univ-pau,dc=fr"
},
"ezpaarse": {
"server": "http://ezpaarse.univ-pau.fr",
"options": [
"geoip: none",
"Output-Fields: +datetime",
"Crypted-Fields: none"
],
"debug": "false"
},
"logpath": "/mnt/data/dev/scd/ezreports/proxy_logs/*.log",
"csvpath": "/mnt/data/dev/scd/ezreports/csv/",
}
def querylaboratoire(ldap, name):
name = name.replace("\\", "\\5C")
name = name.replace("*", "\2A")
name = name.replace("(", "\\28")
name = name.replace(")", "\\29")
name = name.replace("\0", "\\00")
if not ldap.search(
'ou=structures,dc=univ-pau,dc=fr',
"(ou=" + name + ")",
attributes=['supannCodeEntite']):
return None
return ldap.entries[0].supannCodeEntite.value
def connexions2sql(filename, sql):
regex = "^(?P<ip>(?:[0-9]{1,3}\.){3}[0-9]{1,3}) - " \
"(?P<login>[0-9a-zA-Z]*) .*" \
"\[(?P<datetime>.*)\].*connect\?session=.*&url=" \
"https?://w*\.?(?P<url>.[^/]*)/(?P<path>.*) HTTP/1.1.*"
login = re.compile(regex)
# Ouvre le fichier
with open(filename) as file:
# Pour chaque lignes
for line in file:
# Ca match ?
match = login.match(line)
if not match:
continue
url = match.group("url")
date = datetime.strptime(match.group("datetime"), '%d/%b/%Y:%H:%M:%S %z')
# Insertion du lien si inconnu
sql.execute(
"INSERT INTO liens (url, slug, disabled) "
"SELECT %(url)s, %(slug)s, 0 "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM liens WHERE url = %(url)s or slug=%(slug)s) LIMIT 1 ",
params={'url': url, 'slug': slugify(url)})
# Insertion de l'utilisateur si inconnu
sql.execute(
"INSERT INTO utilisateurs (hash) SELECT md5(%(login)s) "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM utilisateurs WHERE hash = md5(%(login)s)) LIMIT 1 ",
params={'login': match.group("login")})
sql.execute(
"INSERT INTO connexions "
"SELECT NULL as id, %(date)s as date, %(time)s as time, md5(%(ip)s) as ip, "
"l.id as lien_id, u.id as utilisateur_id "
"FROM utilisateurs u "
"LEFT JOIN liens l on l.url = %(url)s "
"WHERE u.hash = md5(%(login)s) "
"AND NOT EXISTS (SELECT utilisateur_id FROM connexions WHERE "
"utilisateur_id = u.id AND lien_id = l.id AND date = %(date)s "
"AND time = %(time)s AND ip = md5(%(ip)s))",
params={'login': match.group("login"), 'url': url,
'date': date.strftime("%Y-%m-%d"), 'time': date.strftime("%H:%M:%S"),
'ip': match.group("ip")})
connection.commit()
def log2csv(filename):
ez = config['ezpaarse']
now = datetime.now()
print(str(now) + " Log 2 CSV : \"" + filename + "\"...")
path, file = os.path.split(filename)
# Nom du fichier de sortie
outfile = config['csvpath'] + os.path.splitext(file)[0] + '.csv'
return outfile
# On envoie le fichier de log à ezPAARSE
with open(outfile, "wb") as handle:
c = pycurl.Curl()
if ez['debug'] == "true":
c.setopt(c.VERBOSE, 1)
if ez['options'] is not None:
c.setopt(c.HTTPHEADER, ez['options'])
c.setopt(c.URL, ez["server"])
c.setopt(c.HTTPPOST, [(filename, (c.FORM_FILE, filename))])
c.setopt(c.WRITEDATA, handle)
c.perform()
c.close()
return outfile
def csv2sql(filename, sql):
# now = datetime.now()
print(str(datetime.now()) + " CSV 2 SQL : \"" + filename + "\"")
# Ouvre le fichier csv en lecture
with open(filename, 'r') as csvfile:
#
# Connexion à l'annuaire LDAP
server = ldap3.Server(config['ldap']['server'])
ldap = ldap3.Connection(server,
user=config['ldap']['user'],
password=config['ldap']['pwd'],
auto_bind=True)
for row in csv.DictReader(csvfile, delimiter=';'):
csvhash = ""
for k, v in sorted(row.items()):
csvhash += v
dt = parse(row["datetime"])
login = row["login"]
sql.execute("INSERT IGNORE INTO utilisateurs (hash) SELECT md5(%(login)s) "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM utilisateurs WHERE hash = md5(%(login)s))",
params={'login': login})
if row['publisher_name']:
sql.execute("INSERT INTO editeurs (libelle, slug) SELECT %(libelle)s, %(slug)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM editeurs WHERE slug = %(slug)s) LIMIT 1 ",
params={'libelle': row["publisher_name"], 'slug': slugify(row['publisher_name'])})
if row['platform_name']:
sql.execute("INSERT INTO ressources (libelle, slug) SELECT %(libelle)s, %(slug)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM ressources WHERE slug = %(slug)s) LIMIT 1 ",
params={'slug': slugify(row["platform_name"]), 'libelle': row["platform_name"]})
if row['rtype']:
sql.execute("INSERT INTO types (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM types WHERE code = %(code)s) LIMIT 1 ",
params={'code': row["rtype"]})
if row['mime']:
sql.execute("INSERT INTO formats (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM formats WHERE code = %(code)s) LIMIT 1 ",
params={'code': row["mime"]})
sql.execute("INSERT INTO consultations "
"(JOUR, HEURE, UTILISATEUR_ID, RESSOURCE_ID, EDITEUR_ID, TYPE_ID, FORMAT_ID, HOST, HASH) "
"SELECT %(jour)s, %(heure)s, u.id, r.id, e.id, t.id, f.id, %(host)s, sha1(%(hash)s) "
"FROM (SELECT 1) as tmp "
"LEFT JOIN utilisateurs u on u.hash = md5(%(login)s) "
"LEFT JOIN ressources r on r.slug = %(ressource)s "
"LEFT JOIN formats f on f.code = %(format)s "
"LEFT JOIN types t on t.code = %(type)s "
"LEFT JOIN editeurs e on e.slug = %(editeur)s "
"WHERE NOT EXISTS(SELECT id FROM consultations WHERE hash = sha1(%(hash)s)) "
"LIMIT 1 ",
{
'jour': dt.date(),
'heure': dt.time(),
'login': login,
'ressource': slugify(row["platform_name"]),
'editeur': slugify(row["publisher_name"]),
'type': row["rtype"],
'format': row["mime"],
'host': row["host"],
'hash': csvhash,
})
ec_id = sql.lastrowid
if ec_id == 0:
continue
if not ldap.search(
'ou=people,dc=univ-pau,dc=fr',
"(uid=" + login + ")",
attributes=['supannEtuInscription', 'supannEntiteAffectationPrincipale', 'uppaCodeComp',
'uppaDrhComposante', 'uppaProfil', 'uppaDrhLaboratoire']):
print("No ldap informations for \"" + login + "\"")
continue
infos = ldap.entries[0]._attributes
if not infos:
continue
profils = infos["uppaProfil"].values if "uppaProfil" in infos else ["VIDE"]
for profil in profils:
composante_libelle = None
composante_code = None
laboratoire = None
laboratoire_code = None
diplome_libelle = None
diplome_code = None
cursus_annee = None
if profil == "VIDE":
composante_code = infos["uppaCodeComp"]
composante_libelle = infos["uppaDrhComposante"]
#
# Profil étudiant
elif profil in ("ETU", "AE0", "AE1", "AE2", "AET", "AEP"):
if "supannEtuInscription" in infos:
# Eclate le champ supannEtuInscription
inscriptions = infos["supannEtuInscription"].values
for insc in inscriptions:
insc = insc.replace("[", "").split("]")
for d in insc:
d = d.split("=")
if d[0] == "cursusann":
cursus_annee = d[1].replace("{SUPANN}", "")
if d[0] == "libDiplome":
diplome_libelle = d[1]
if d[0] == "diplome":
diplome_code = d[1].replace("{SISE}", "")
else:
cursus_annee = ""
diplome_libelle = infos["uppaDrhComposante"] if "uppaDrhComposante" in infos else None
if isinstance(diplome_libelle, list):
diplome_libelle = diplome_libelle[0]
diplome_code = infos["uppaCodeComp"] if "uppaCodeComp" in infos else None
if isinstance(diplome_code, list):
diplome_code = diplome_code[0]
#
# Profil personnel
elif profil in ("PER", "DOC", "VAC", "INV", "APE", "HEB", "ANC", "APH", "CET", "EME", "LEC",
"PVA", "PAD", "PEC", "STA", "ADM", "AP0", "PAR", "PPE", "ADC", "RSS", "AD0"):
#
# Composante
if "supannEntiteAffectationPrincipale" in infos:
composante_code = infos["supannEntiteAffectationPrincipale"].value
if len(infos["uppaCodeComp"]) > 1:
for id, code in enumerate(infos["uppaCodeComp"]):
if code == composante_code:
composante_libelle = infos["uppaDrhComposante"][id]
break
else:
composante_libelle = infos["uppaDrhComposante"].value
else:
composante_code = infos["uppaCodeComp"].value if "uppaCodeComp" in infos else ""
composante_libelle = infos["uppaDrhComposante"].value if "uppaDrhComposante" in infos else ""
#
# Laboratoire
if "uppaDrhLaboratoire" in infos:
laboratoire = infos["uppaDrhLaboratoire"][0].value \
if isinstance(infos["uppaDrhLaboratoire"], list) else infos["uppaDrhLaboratoire"].value
# todo: Par défaut, prend le premier enregistrement
if isinstance(laboratoire, list):
laboratoire = laboratoire[0]
laboratoire_code = querylaboratoire(ldap, laboratoire)
else:
#print("Profil non géré : " + profil)
continue
#
# Insère les données manquants
sql.execute("INSERT INTO profils (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM profils WHERE code = %(code)s) LIMIT 1 ",
params={'code': profil})
if composante_code is not None and composante_code != 0 \
and composante_libelle is not None and composante_libelle != "":
sql.execute("INSERT INTO composantes (code, libelle) "
"SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT code FROM composantes WHERE code = %(code)s) LIMIT 1 ",
{'code': composante_code, 'libelle': composante_libelle})
# todo: Gérer le cas il y a plusieurs diplomes
if diplome_code is not None and diplome_libelle is not None:
sql.execute("REPLACE INTO diplomes (code, libelle) SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM diplomes WHERE code = %(code)s) LIMIT 1 ",
{'code': diplome_code, 'libelle': diplome_libelle})
if cursus_annee != "" and cursus_annee is not None:
sql.execute("INSERT INTO cursus (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM cursus WHERE code = %(code)s) LIMIT 1 ",
params={'code': cursus_annee})
if laboratoire != "" and laboratoire is not None:
sql.execute("INSERT INTO laboratoires (code, libelle) SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM laboratoires WHERE code = %(code)s "
"or libelle = %(libelle)s) LIMIT 1 ",
params={'code': laboratoire_code, 'libelle': laboratoire})
sql.execute("INSERT IGNORE INTO meta "
"(consultation_id, profil_id, composante_id, laboratoire_id, diplome_id, cursus_id) "
"SELECT %(consultation)s, p.id, co.id, l.id, d.id, c.id "
"FROM profils p "
"LEFT JOIN laboratoires l on l.libelle = %(laboratoire)s "
"LEFT JOIN diplomes d on d.code = %(diplome)s "
"LEFT JOIN cursus c on c.code = %(cursus)s "
"LEFT JOIN composantes co on co.id = %(composante)s "
"WHERE p.code = %(profil)s",
{
'consultation': ec_id,
'profil': profil,
'composante': composante_code,
'laboratoire': laboratoire,
'diplome': diplome_code,
'cursus': cursus_annee
})
connection.commit()
class Command(BaseCommand):
args = '<team_id>'
help = 'Process raw logs from the reverse proxy and import them in database'
def add_arguments(self, parser):
parser.add_argument('--min-date',
help="Everything before this date is ignored (dd/mm/yyyy)",
#default=date.today() - timedelta(1),
required=False)
def handle(self, *args, **options):
# Si aucun argument, on prend depuis la dernière date en base
if not options['min_date']:
#
# Date du dernier fichier traité
query = Connexion.objects.all().aggregate(Max('date'))
mindate = datetime(query['date__max'].year, query['date__max'].month, query['date__max'].day - 1)
else:
try:
mindate = datetime.strptime(options['min_date'], '%d/%m/%Y',)
except ValueError:
raise CommandError('Invalide min-date format !')
# Connexion SQL
sql = connection.cursor()
# Pour chaque fichier de log à traiter
for logfile in sorted(glob.glob(config['logpath'])):
# format du fichier 'ezproxy-YYYY.MM.DD.log'
filename = os.path.split(logfile)[1]
filedate = datetime.strptime(filename, 'ezproxy-%Y.%m.%d.log')
if filedate < mindate:
continue
self.stdout.write("Processing '{}'".format(os.path.basename(logfile)))
#
# Importe les connexions
#
connexions2sql(logfile, sql)
#
# Envoie les données au serveur EZPaarse
#
csvfile = log2csv(logfile)
#
# Envoie les données d'EZPaarse en base sql
csv2sql(csvfile, sql)
| true | true |
f72c46cc6e6046ea77fc6de5d29eb113534e9e14 | 9,731 | py | Python | tools/rosunit/test/test_junitxml.py | dodsonmg/ros | f1ce3d9d36e8df9dcdca6b37086aabb7f3e202d3 | [
"BSD-3-Clause"
] | null | null | null | tools/rosunit/test/test_junitxml.py | dodsonmg/ros | f1ce3d9d36e8df9dcdca6b37086aabb7f3e202d3 | [
"BSD-3-Clause"
] | null | null | null | tools/rosunit/test/test_junitxml.py | dodsonmg/ros | f1ce3d9d36e8df9dcdca6b37086aabb7f3e202d3 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id: $
import os
import io
import sys
import unittest
import tempfile
import shutil
junitxml = None
## Basic test of xmlresult functionality of reading gtest xml files and
## summarizing their results into a new file.
class MockResult():
def __init__(self, directory, filename, suites = [], noSuitesRoot = False):
self.filename = os.path.join(directory, filename)
self.suites = suites
# whether to suppress <testsuites> root node
self.noSuitesRoot = noSuitesRoot
class MockSuite():
def __init__(self, cases, name, tests = 0, errors = 0, fail = 0, time = 1):
self.cases = cases
self.tests = tests
self.time = time
self.fail = fail
self.errors = errors
self.name = name
class MockCase():
def __init__(self, name, errorList = [], classname="", time = 1):
self.classname = classname
self.name = name
self.time = time
self.errorList = errorList
class MockErrorType(Exception):
def __init__(self, value, etype = ''):
self.value = value
self.__name__ = value
self.type = etype
def _writeMockResultFile(result):
"writes a test result as a gtest compatible test runner would do"
with open(result.filename, 'w') as f:
f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
if len(result.suites) > 1 or result.noSuitesRoot == False:
f.write('<testsuites>\n')
for suite in result.suites:
f.write('<testsuite tests="'+str(suite.tests)+'" failures="'+str(suite.fail)+'" time="'+str(suite.time)+'" errors="'+str(suite.errors)+'" name="'+suite.name+'">\n')
for case in suite.cases:
f.write('<testcase name="'+case.name+'" status="run" time="'+str(case.time)+'" classname="'+case.classname+'">\n')
for error in case.errorList:
f.write('<failure message="'+error.value+'" type="'+error.value+'"/>\n')
f.write('</testcase>\n')
f.write('</testsuite>\n')
if len(result.suites) > 1 or result.noSuitesRoot == False:
f.write('</testsuites>\n')
class XmlResultTestGeneration(unittest.TestCase):
def setUp(self):
global junitxml
if junitxml is None:
import rosunit.junitxml
junitxml = rosunit.junitxml
def tearDown(self):
pass
def testGenerateError(self):
error = junitxml.TestError('error_type', 'error_text')
error_str = error.xml()
self.assertEquals(b'''<error type="error_type"><![CDATA[
error_text
]]></error>''', error_str)
def testGenerateFailure(self):
failure = junitxml.TestFailure('failure_type', 'failure_text')
failure_str = failure.xml()
self.assertEquals(b'''<failure type="failure_type"><![CDATA[
failure_text
]]></failure>''', failure_str)
def testGenerateTestCaseResult(self):
testcase = junitxml.TestCaseResult('test_case')
error = junitxml.TestError('error_type', 'error_text')
error_str = error.xml()
failure = junitxml.TestFailure('failure_type', 'failure_text')
failure_str = failure.xml()
testcase.add_error(error)
testcase.add_failure(failure)
testcase_str = testcase.xml()
self.assertEquals(b'''<testcase classname="" name="test_case" time="0.0"><failure type="failure_type"><![CDATA[
failure_text
]]></failure><error type="error_type"><![CDATA[
error_text
]]></error></testcase>''', testcase_str)
class XmlResultTestRead(unittest.TestCase):
def setUp(self):
# lazy-import to get coverage
global junitxml
if junitxml is None:
import rosunit.junitxml
junitxml = rosunit.junitxml
self.directory = tempfile.mkdtemp()
# setting up mock results as dict so results can be checked individually
self.mockresults={
"empty": MockResult(self.directory, "empty.xml", []),
"emptysuite": MockResult(self.directory, "emptysuite.xml", [MockSuite([], "emptySuite", 0, 0, 0, 0)]),
"succ1": MockResult(self.directory, "succ1.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1)]),
"err1": MockResult(self.directory, "err1.xml", [MockSuite([MockCase("errCase")],"err1suite", 1, 1, 0, 1)]),
"fail1": MockResult(self.directory, "fail1.xml", [MockSuite([MockCase("failCase")],"fail1suite", 1, 0, 1, 1)]),
"noroot": MockResult(self.directory, "succ1.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1)], noSuitesRoot = True),
"multicase": MockResult(self.directory,
"multicase.xml",
[MockSuite([MockCase("succCase"),
MockCase("errCase"),
MockCase("failCase")],
"succ1suite", 3, 1, 1, time = 3)]),
"multisuite": MockResult(self.directory,
"multisuite.xml",
[MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1),
MockSuite([MockCase("errCase")],"err1suite", 1, 1, 0, 1),
MockSuite([MockCase("failCase")],"fail1suite", 1, 0, 1, 1)])
}
for name, result in self.mockresults.items():
_writeMockResultFile(result)
def tearDown(self):
shutil.rmtree(self.directory)
#pass
def testReadNoSuites(self):
result = junitxml.read(self.mockresults["empty"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(0.0, result.time)
self.assertEquals(0, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadEmptySuite(self):
result = junitxml.read(self.mockresults["emptysuite"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(0.0, result.time)
self.assertEquals(0, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadSuccess(self):
result = junitxml.read(self.mockresults["succ1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadError(self):
result = junitxml.read(self.mockresults["err1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadFail(self):
result = junitxml.read(self.mockresults["fail1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(1, result.num_failures)
def testReadMulticase(self):
result = junitxml.read(self.mockresults["multicase"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(3.0, result.time)
self.assertEquals(3, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(1, result.num_failures)
def testReadMultisuite(self):
result = junitxml.read(self.mockresults["multisuite"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(3.0, result.time)
self.assertEquals(3, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(1, result.num_failures)
| 42.679825 | 176 | 0.631795 |
import os
import io
import sys
import unittest
import tempfile
import shutil
junitxml = None
.filename = os.path.join(directory, filename)
self.suites = suites
self.noSuitesRoot = noSuitesRoot
class MockSuite():
def __init__(self, cases, name, tests = 0, errors = 0, fail = 0, time = 1):
self.cases = cases
self.tests = tests
self.time = time
self.fail = fail
self.errors = errors
self.name = name
class MockCase():
def __init__(self, name, errorList = [], classname="", time = 1):
self.classname = classname
self.name = name
self.time = time
self.errorList = errorList
class MockErrorType(Exception):
def __init__(self, value, etype = ''):
self.value = value
self.__name__ = value
self.type = etype
def _writeMockResultFile(result):
with open(result.filename, 'w') as f:
f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
if len(result.suites) > 1 or result.noSuitesRoot == False:
f.write('<testsuites>\n')
for suite in result.suites:
f.write('<testsuite tests="'+str(suite.tests)+'" failures="'+str(suite.fail)+'" time="'+str(suite.time)+'" errors="'+str(suite.errors)+'" name="'+suite.name+'">\n')
for case in suite.cases:
f.write('<testcase name="'+case.name+'" status="run" time="'+str(case.time)+'" classname="'+case.classname+'">\n')
for error in case.errorList:
f.write('<failure message="'+error.value+'" type="'+error.value+'"/>\n')
f.write('</testcase>\n')
f.write('</testsuite>\n')
if len(result.suites) > 1 or result.noSuitesRoot == False:
f.write('</testsuites>\n')
class XmlResultTestGeneration(unittest.TestCase):
def setUp(self):
global junitxml
if junitxml is None:
import rosunit.junitxml
junitxml = rosunit.junitxml
def tearDown(self):
pass
def testGenerateError(self):
error = junitxml.TestError('error_type', 'error_text')
error_str = error.xml()
self.assertEquals(b'''<error type="error_type"><![CDATA[
error_text
]]></error>''', error_str)
def testGenerateFailure(self):
failure = junitxml.TestFailure('failure_type', 'failure_text')
failure_str = failure.xml()
self.assertEquals(b'''<failure type="failure_type"><![CDATA[
failure_text
]]></failure>''', failure_str)
def testGenerateTestCaseResult(self):
testcase = junitxml.TestCaseResult('test_case')
error = junitxml.TestError('error_type', 'error_text')
error_str = error.xml()
failure = junitxml.TestFailure('failure_type', 'failure_text')
failure_str = failure.xml()
testcase.add_error(error)
testcase.add_failure(failure)
testcase_str = testcase.xml()
self.assertEquals(b'''<testcase classname="" name="test_case" time="0.0"><failure type="failure_type"><![CDATA[
failure_text
]]></failure><error type="error_type"><![CDATA[
error_text
]]></error></testcase>''', testcase_str)
class XmlResultTestRead(unittest.TestCase):
def setUp(self):
global junitxml
if junitxml is None:
import rosunit.junitxml
junitxml = rosunit.junitxml
self.directory = tempfile.mkdtemp()
self.mockresults={
"empty": MockResult(self.directory, "empty.xml", []),
"emptysuite": MockResult(self.directory, "emptysuite.xml", [MockSuite([], "emptySuite", 0, 0, 0, 0)]),
"succ1": MockResult(self.directory, "succ1.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1)]),
"err1": MockResult(self.directory, "err1.xml", [MockSuite([MockCase("errCase")],"err1suite", 1, 1, 0, 1)]),
"fail1": MockResult(self.directory, "fail1.xml", [MockSuite([MockCase("failCase")],"fail1suite", 1, 0, 1, 1)]),
"noroot": MockResult(self.directory, "succ1.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1)], noSuitesRoot = True),
"multicase": MockResult(self.directory,
"multicase.xml",
[MockSuite([MockCase("succCase"),
MockCase("errCase"),
MockCase("failCase")],
"succ1suite", 3, 1, 1, time = 3)]),
"multisuite": MockResult(self.directory,
"multisuite.xml",
[MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1),
MockSuite([MockCase("errCase")],"err1suite", 1, 1, 0, 1),
MockSuite([MockCase("failCase")],"fail1suite", 1, 0, 1, 1)])
}
for name, result in self.mockresults.items():
_writeMockResultFile(result)
def tearDown(self):
shutil.rmtree(self.directory)
def testReadNoSuites(self):
result = junitxml.read(self.mockresults["empty"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(0.0, result.time)
self.assertEquals(0, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadEmptySuite(self):
result = junitxml.read(self.mockresults["emptysuite"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(0.0, result.time)
self.assertEquals(0, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadSuccess(self):
result = junitxml.read(self.mockresults["succ1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadError(self):
result = junitxml.read(self.mockresults["err1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadFail(self):
result = junitxml.read(self.mockresults["fail1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(1, result.num_failures)
def testReadMulticase(self):
result = junitxml.read(self.mockresults["multicase"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(3.0, result.time)
self.assertEquals(3, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(1, result.num_failures)
def testReadMultisuite(self):
result = junitxml.read(self.mockresults["multisuite"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(3.0, result.time)
self.assertEquals(3, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(1, result.num_failures)
| true | true |
f72c4791408d215f1552686fbe6b4975707a7ebe | 63 | py | Python | python/testData/refactoring/changeSignature/keywordOnlyMove.before.py | truthiswill/intellij-community | fff88cfb0dc168eea18ecb745d3e5b93f57b0b95 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | python/testData/refactoring/changeSignature/keywordOnlyMove.before.py | truthiswill/intellij-community | fff88cfb0dc168eea18ecb745d3e5b93f57b0b95 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | python/testData/refactoring/changeSignature/keywordOnlyMove.before.py | truthiswill/intellij-community | fff88cfb0dc168eea18ecb745d3e5b93f57b0b95 | [
"Apache-2.0"
] | 2 | 2020-03-15T08:57:37.000Z | 2020-04-07T04:48:14.000Z | def f<caret>(*, param1, param2):
pass
f(param1=1, param2=2) | 12.6 | 32 | 0.634921 | def f<caret>(*, param1, param2):
pass
f(param1=1, param2=2) | false | true |
f72c48af45b656ece0447e4d40290a0102816591 | 20,906 | py | Python | odoo/base-addons/sale/tests/test_sale_product_attribute_value_config.py | LucasBorges-Santos/docker-odoo | 53987bbd61f6119669b5f801ee2ad54695084a21 | [
"MIT"
] | null | null | null | odoo/base-addons/sale/tests/test_sale_product_attribute_value_config.py | LucasBorges-Santos/docker-odoo | 53987bbd61f6119669b5f801ee2ad54695084a21 | [
"MIT"
] | null | null | null | odoo/base-addons/sale/tests/test_sale_product_attribute_value_config.py | LucasBorges-Santos/docker-odoo | 53987bbd61f6119669b5f801ee2ad54695084a21 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields
from odoo.addons.product.tests.test_product_attribute_value_config import TestProductAttributeValueSetup
from odoo.tests import tagged
class TestSaleProductAttributeValueSetup(TestProductAttributeValueSetup):
def _setup_currency(self, currency_ratio=2):
"""Get or create a currency. This makes the test non-reliant on demo.
With an easy currency rate, for a simple 2 ratio in the following tests.
"""
from_currency = self.computer.currency_id
self._set_or_create_rate_today(from_currency, rate=1)
to_currency = self._get_or_create_currency("my currency", "C")
self._set_or_create_rate_today(to_currency, currency_ratio)
return to_currency
def _set_or_create_rate_today(self, currency, rate):
"""Get or create a currency rate for today. This makes the test
non-reliant on demo data."""
name = fields.Date.today()
currency_id = currency.id
company_id = self.env.company.id
CurrencyRate = self.env['res.currency.rate']
currency_rate = CurrencyRate.search([
('company_id', '=', company_id),
('currency_id', '=', currency_id),
('name', '=', name),
])
if currency_rate:
currency_rate.rate = rate
else:
CurrencyRate.create({
'company_id': company_id,
'currency_id': currency_id,
'name': name,
'rate': rate,
})
def _get_or_create_currency(self, name, symbol):
"""Get or create a currency based on name. This makes the test
non-reliant on demo data."""
currency = self.env['res.currency'].search([('name', '=', name)])
return currency or currency.create({
'name': name,
'symbol': symbol,
})
@tagged('post_install', '-at_install')
class TestSaleProductAttributeValueConfig(TestSaleProductAttributeValueSetup):
def _setup_pricelist(self, currency_ratio=2):
to_currency = self._setup_currency(currency_ratio)
discount = 10
pricelist = self.env['product.pricelist'].create({
'name': 'test pl',
'currency_id': to_currency.id,
'company_id': self.computer.company_id.id,
})
pricelist_item = self.env['product.pricelist.item'].create({
'min_quantity': 2,
'compute_price': 'percentage',
'percent_price': discount,
'pricelist_id': pricelist.id,
})
return (pricelist, pricelist_item, currency_ratio, 1 - discount / 100)
def test_01_is_combination_possible_archived(self):
"""The goal is to test the possibility of archived combinations.
This test could not be put into product module because there was no
model which had product_id as required and without cascade on delete.
Here we have the sales order line in this situation.
This is a necessary condition for `_create_variant_ids` to archive
instead of delete the variants.
"""
def do_test(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
variant2 = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_2)
self.assertTrue(variant)
self.assertTrue(variant2)
# Create a dummy SO to prevent the variant from being deleted by
# _create_variant_ids() because the variant is a related field that
# is required on the SO line
so = self.env['sale.order'].create({'partner_id': 1})
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant.id
})
# additional variant to test correct ignoring when mismatch values
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant2.id
})
variant2.active = False
# CASE: 1 not archived, 2 archived
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_2))
# CASE: both archived combination (without no_variant)
variant.active = False
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_2))
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: OK after attribute line removed
self.computer_hdd_attribute_lines.unlink()
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8))
# CASE: not archived (with no_variant)
self.hdd_attribute.create_variant = 'no_variant'
self._add_hdd_attribute_line()
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: archived combination found (with no_variant)
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
variant.active = False
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: archived combination has different attributes (including no_variant)
self.computer_ssd_attribute_lines.unlink()
variant4 = self.computer._get_variant_for_combination(computer_ram_8 + computer_hdd_1)
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant4.id
})
self.assertTrue(self.computer._is_combination_possible(computer_ram_8 + computer_hdd_1))
# CASE: archived combination has different attributes (without no_variant)
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'always'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
variant5 = self.computer._get_variant_for_combination(computer_ram_8 + computer_hdd_1)
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant5.id
})
self.assertTrue(variant4 != variant5)
self.assertTrue(self.computer._is_combination_possible(computer_ram_8 + computer_hdd_1))
computer_ssd_256_before = self._get_product_template_attribute_value(self.ssd_256)
do_test(self)
# CASE: add back the removed attribute and try everything again
self.computer_ssd_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer.id,
'attribute_id': self.ssd_attribute.id,
'value_ids': [(6, 0, [self.ssd_256.id, self.ssd_512.id])],
})
computer_ssd_256_after = self._get_product_template_attribute_value(self.ssd_256)
self.assertEqual(computer_ssd_256_after, computer_ssd_256_before)
self.assertEqual(computer_ssd_256_after.attribute_line_id, computer_ssd_256_before.attribute_line_id)
do_test(self)
def test_02_get_combination_info(self):
# If using multi-company, company_id will be False, and this code should
# still work.
# The case with a company_id will be implicitly tested on website_sale.
self.computer.company_id = False
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
# CASE: no pricelist, no currency, with existing combination, with price_extra on attributes
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant = self.computer._get_variant_for_combination(combination)
res = self.computer._get_combination_info(combination)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222)
self.assertEqual(res['list_price'], 2222)
self.assertEqual(res['price_extra'], 222)
# CASE: no combination, product given
res = self.computer._get_combination_info(self.env['product.template.attribute.value'], computer_variant.id)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222)
self.assertEqual(res['list_price'], 2222)
self.assertEqual(res['price_extra'], 222)
# CASE: using pricelist, quantity rule
pricelist, pricelist_item, currency_ratio, discount_ratio = self._setup_pricelist()
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: no_variant combination, it's another variant now
self.computer_ssd_attribute_lines.unlink()
self.ssd_attribute.create_variant = 'no_variant'
self._add_ssd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant_new = self.computer._get_variant_for_combination(combination)
self.assertTrue(computer_variant_new)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant_new.id)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: dynamic combination, but the variant already exists
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'dynamic'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant_new = self.computer._create_product_variant(combination)
self.assertTrue(computer_variant_new)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant_new.id)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: dynamic combination, no variant existing
# Test invalidate_cache on product.template _create_variant_ids
self._add_keyboard_attribute()
combination += self._get_product_template_attribute_value(self.keyboard_excluded)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], False)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To, Excluded)")
self.assertEqual(res['price'], (2222 - 5) * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], (2222 - 5) * currency_ratio)
self.assertEqual(res['price_extra'], (222 - 5) * currency_ratio)
# CASE: pricelist set value to 0, no variant
# Test invalidate_cache on product.pricelist write
pricelist_item.percent_price = 100
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], False)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To, Excluded)")
self.assertEqual(res['price'], 0)
self.assertEqual(res['list_price'], (2222 - 5) * currency_ratio)
self.assertEqual(res['price_extra'], (222 - 5) * currency_ratio)
def test_03_get_combination_info_discount_policy(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
pricelist, pricelist_item, currency_ratio, discount_ratio = self._setup_pricelist()
pricelist.discount_policy = 'with_discount'
# CASE: no discount, setting with_discount
res = self.computer._get_combination_info(combination, add_qty=1, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: discount, setting with_discount
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: no discount, setting without_discount
pricelist.discount_policy = 'without_discount'
res = self.computer._get_combination_info(combination, add_qty=1, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: discount, setting without_discount
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], True)
def test_04_create_product_variant_non_dynamic(self):
"""The goal of this test is to make sure the create_product_variant does
not create variant if the type is not dynamic. It can however return a
variant if it already exists."""
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: variant is already created, it should return it
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
variant1 = self.computer._get_variant_for_combination(combination)
self.assertEqual(self.computer._create_product_variant(combination), variant1)
# CASE: variant does not exist, but template is non-dynamic, so it
# should not create it
Product = self.env['product.product']
variant1.unlink()
self.assertEqual(self.computer._create_product_variant(combination), Product)
def test_05_create_product_variant_dynamic(self):
"""The goal of this test is to make sure the create_product_variant does
work with dynamic. If the combination is possible, it should create it.
If it's not possible, it should not create it."""
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'dynamic'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: variant does not exist, but combination is not possible
# so it should not create it
impossible_combination = computer_ssd_256 + computer_ram_16 + computer_hdd_1
Product = self.env['product.product']
self.assertEqual(self.computer._create_product_variant(impossible_combination), Product)
# CASE: the variant does not exist, and the combination is possible, so
# it should create it
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
variant = self.computer._create_product_variant(combination)
self.assertTrue(variant)
# CASE: the variant already exists, so it should return it
self.assertEqual(variant, self.computer._create_product_variant(combination))
def _add_keyboard_attribute(self):
self.keyboard_attribute = self.env['product.attribute'].create({
'name': 'Keyboard',
'sequence': 6,
'create_variant': 'dynamic',
})
self.keyboard_included = self.env['product.attribute.value'].create({
'name': 'Included',
'attribute_id': self.keyboard_attribute.id,
'sequence': 1,
})
self.keyboard_excluded = self.env['product.attribute.value'].create({
'name': 'Excluded',
'attribute_id': self.keyboard_attribute.id,
'sequence': 2,
})
self.computer_keyboard_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer.id,
'attribute_id': self.keyboard_attribute.id,
'value_ids': [(6, 0, [self.keyboard_included.id, self.keyboard_excluded.id])],
})
self.computer_keyboard_attribute_lines.product_template_value_ids[0].price_extra = 5
self.computer_keyboard_attribute_lines.product_template_value_ids[1].price_extra = -5
| 51.114914 | 120 | 0.69162 |
from odoo import fields
from odoo.addons.product.tests.test_product_attribute_value_config import TestProductAttributeValueSetup
from odoo.tests import tagged
class TestSaleProductAttributeValueSetup(TestProductAttributeValueSetup):
def _setup_currency(self, currency_ratio=2):
from_currency = self.computer.currency_id
self._set_or_create_rate_today(from_currency, rate=1)
to_currency = self._get_or_create_currency("my currency", "C")
self._set_or_create_rate_today(to_currency, currency_ratio)
return to_currency
def _set_or_create_rate_today(self, currency, rate):
name = fields.Date.today()
currency_id = currency.id
company_id = self.env.company.id
CurrencyRate = self.env['res.currency.rate']
currency_rate = CurrencyRate.search([
('company_id', '=', company_id),
('currency_id', '=', currency_id),
('name', '=', name),
])
if currency_rate:
currency_rate.rate = rate
else:
CurrencyRate.create({
'company_id': company_id,
'currency_id': currency_id,
'name': name,
'rate': rate,
})
def _get_or_create_currency(self, name, symbol):
currency = self.env['res.currency'].search([('name', '=', name)])
return currency or currency.create({
'name': name,
'symbol': symbol,
})
@tagged('post_install', '-at_install')
class TestSaleProductAttributeValueConfig(TestSaleProductAttributeValueSetup):
def _setup_pricelist(self, currency_ratio=2):
to_currency = self._setup_currency(currency_ratio)
discount = 10
pricelist = self.env['product.pricelist'].create({
'name': 'test pl',
'currency_id': to_currency.id,
'company_id': self.computer.company_id.id,
})
pricelist_item = self.env['product.pricelist.item'].create({
'min_quantity': 2,
'compute_price': 'percentage',
'percent_price': discount,
'pricelist_id': pricelist.id,
})
return (pricelist, pricelist_item, currency_ratio, 1 - discount / 100)
def test_01_is_combination_possible_archived(self):
def do_test(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
variant2 = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_2)
self.assertTrue(variant)
self.assertTrue(variant2)
so = self.env['sale.order'].create({'partner_id': 1})
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant.id
})
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant2.id
})
variant2.active = False
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_2))
variant.active = False
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_2))
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
self.computer_hdd_attribute_lines.unlink()
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8))
self.hdd_attribute.create_variant = 'no_variant'
self._add_hdd_attribute_line()
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
variant.active = False
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
self.computer_ssd_attribute_lines.unlink()
variant4 = self.computer._get_variant_for_combination(computer_ram_8 + computer_hdd_1)
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant4.id
})
self.assertTrue(self.computer._is_combination_possible(computer_ram_8 + computer_hdd_1))
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'always'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
variant5 = self.computer._get_variant_for_combination(computer_ram_8 + computer_hdd_1)
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant5.id
})
self.assertTrue(variant4 != variant5)
self.assertTrue(self.computer._is_combination_possible(computer_ram_8 + computer_hdd_1))
computer_ssd_256_before = self._get_product_template_attribute_value(self.ssd_256)
do_test(self)
self.computer_ssd_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer.id,
'attribute_id': self.ssd_attribute.id,
'value_ids': [(6, 0, [self.ssd_256.id, self.ssd_512.id])],
})
computer_ssd_256_after = self._get_product_template_attribute_value(self.ssd_256)
self.assertEqual(computer_ssd_256_after, computer_ssd_256_before)
self.assertEqual(computer_ssd_256_after.attribute_line_id, computer_ssd_256_before.attribute_line_id)
do_test(self)
def test_02_get_combination_info(self):
self.computer.company_id = False
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant = self.computer._get_variant_for_combination(combination)
res = self.computer._get_combination_info(combination)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222)
self.assertEqual(res['list_price'], 2222)
self.assertEqual(res['price_extra'], 222)
res = self.computer._get_combination_info(self.env['product.template.attribute.value'], computer_variant.id)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222)
self.assertEqual(res['list_price'], 2222)
self.assertEqual(res['price_extra'], 222)
pricelist, pricelist_item, currency_ratio, discount_ratio = self._setup_pricelist()
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.computer_ssd_attribute_lines.unlink()
self.ssd_attribute.create_variant = 'no_variant'
self._add_ssd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant_new = self.computer._get_variant_for_combination(combination)
self.assertTrue(computer_variant_new)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant_new.id)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: dynamic combination, but the variant already exists
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'dynamic'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant_new = self.computer._create_product_variant(combination)
self.assertTrue(computer_variant_new)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant_new.id)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: dynamic combination, no variant existing
# Test invalidate_cache on product.template _create_variant_ids
self._add_keyboard_attribute()
combination += self._get_product_template_attribute_value(self.keyboard_excluded)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], False)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To, Excluded)")
self.assertEqual(res['price'], (2222 - 5) * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], (2222 - 5) * currency_ratio)
self.assertEqual(res['price_extra'], (222 - 5) * currency_ratio)
# CASE: pricelist set value to 0, no variant
# Test invalidate_cache on product.pricelist write
pricelist_item.percent_price = 100
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], False)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To, Excluded)")
self.assertEqual(res['price'], 0)
self.assertEqual(res['list_price'], (2222 - 5) * currency_ratio)
self.assertEqual(res['price_extra'], (222 - 5) * currency_ratio)
def test_03_get_combination_info_discount_policy(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
pricelist, pricelist_item, currency_ratio, discount_ratio = self._setup_pricelist()
pricelist.discount_policy = 'with_discount'
# CASE: no discount, setting with_discount
res = self.computer._get_combination_info(combination, add_qty=1, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: discount, setting with_discount
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: no discount, setting without_discount
pricelist.discount_policy = 'without_discount'
res = self.computer._get_combination_info(combination, add_qty=1, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: discount, setting without_discount
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], True)
def test_04_create_product_variant_non_dynamic(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: variant is already created, it should return it
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
variant1 = self.computer._get_variant_for_combination(combination)
self.assertEqual(self.computer._create_product_variant(combination), variant1)
# CASE: variant does not exist, but template is non-dynamic, so it
# should not create it
Product = self.env['product.product']
variant1.unlink()
self.assertEqual(self.computer._create_product_variant(combination), Product)
def test_05_create_product_variant_dynamic(self):
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'dynamic'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: variant does not exist, but combination is not possible
# so it should not create it
impossible_combination = computer_ssd_256 + computer_ram_16 + computer_hdd_1
Product = self.env['product.product']
self.assertEqual(self.computer._create_product_variant(impossible_combination), Product)
# CASE: the variant does not exist, and the combination is possible, so
# it should create it
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
variant = self.computer._create_product_variant(combination)
self.assertTrue(variant)
# CASE: the variant already exists, so it should return it
self.assertEqual(variant, self.computer._create_product_variant(combination))
def _add_keyboard_attribute(self):
self.keyboard_attribute = self.env['product.attribute'].create({
'name': 'Keyboard',
'sequence': 6,
'create_variant': 'dynamic',
})
self.keyboard_included = self.env['product.attribute.value'].create({
'name': 'Included',
'attribute_id': self.keyboard_attribute.id,
'sequence': 1,
})
self.keyboard_excluded = self.env['product.attribute.value'].create({
'name': 'Excluded',
'attribute_id': self.keyboard_attribute.id,
'sequence': 2,
})
self.computer_keyboard_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer.id,
'attribute_id': self.keyboard_attribute.id,
'value_ids': [(6, 0, [self.keyboard_included.id, self.keyboard_excluded.id])],
})
self.computer_keyboard_attribute_lines.product_template_value_ids[0].price_extra = 5
self.computer_keyboard_attribute_lines.product_template_value_ids[1].price_extra = -5
| true | true |
f72c490d26e31fc870e558ebe85f5de8ccd13aa9 | 4,921 | py | Python | src/btfs/firebase_dc.py | mikespub-org/mar10-clouddav | dabfe2832438667ca5ff960e9273fceae9280f15 | [
"MIT"
] | 2 | 2021-03-01T10:27:41.000Z | 2021-11-04T21:27:12.000Z | src/btfs/firebase_dc.py | mikespub-org/mar10-clouddav | dabfe2832438667ca5ff960e9273fceae9280f15 | [
"MIT"
] | 1 | 2022-03-07T09:09:21.000Z | 2022-03-07T09:09:21.000Z | src/btfs/firebase_dc.py | mikespub-org/mar10-clouddav | dabfe2832438667ca5ff960e9273fceae9280f15 | [
"MIT"
] | 1 | 2020-10-17T07:35:37.000Z | 2020-10-17T07:35:37.000Z | # (c) 2009-2019 Martin Wendt and contributors; see WsgiDAV https://github.com/mar10/wsgidav
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Implementation of a domain controller that allows users to authenticate via the
Google Identity Platform - based on Firebase Authentication.
Used by HTTPAuthenticator. Only for web-based access or behind an identity-aware proxy.
See https://wsgidav.readthedocs.io/en/latest/user_guide_configure.html
"""
from wsgidav import util
from wsgidav.dc.base_dc import BaseDomainController
from .sessions import get_current_session
__docformat__ = "reStructuredText"
_logger = util.get_module_logger(__name__)
class FirebaseDomainController(BaseDomainController):
known_roles = ("admin", "editor", "reader", "browser", "none")
def __init__(self, wsgidav_app, config):
super().__init__(wsgidav_app, config)
# auth_conf = config["http_authenticator"]
dc_conf = config.get("firebase_dc", {})
self.project_id = dc_conf.get("project_id", None)
self.api_key = dc_conf.get("api_key", None)
self.id_token = dc_conf.get("id_token", "id_token")
self.user_role = dc_conf.get("user_role", "reader")
self.anon_role = dc_conf.get("anon_role", "browser")
def __str__(self):
return f"{self.__class__.__name__}('{self.project_id}')"
def get_domain_realm(self, path_info, environ):
return f"Firebase({self.project_id})"
def require_authentication(self, realm, environ):
# TODO: check id_token or trusted_auth_header
# environ["wsgidav.auth.user_name"] = ""
# The domain controller MAY set those values depending on user's
# authorization:
# environ["wsgidav.auth.roles"] = None
# environ["wsgidav.auth.permissions"] = None
# "wsgidav.auth.realm": "Firebase(...)"
if not environ:
return True
_logger.debug("Realm: %s" % realm)
# "wsgidav.auth.user_name": "",
if environ.get("wsgidav.auth.user_name"):
_logger.debug("User: %s" % environ.get("wsgidav.auth.user_name"))
return False
# "wsgidav.config": {...}
config = environ.get("wsgidav.config", {})
auth_conf = config.get("http_authenticator", {})
trusted_auth_header = auth_conf.get("trusted_auth_header", None)
if trusted_auth_header and environ.get(trusted_auth_header):
environ["wsgidav.auth.user_name"] = environ.get(trusted_auth_header)
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = [self.user_role]
_logger.debug("Trusted: %s" % environ.get("wsgidav.auth.user_name"))
return False
# "HTTP_COOKIE": "..."
session = get_current_session(environ)
if session.is_user():
environ["wsgidav.auth.user_name"] = session.user_id
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = []
for role in session.get_roles():
if (
role in self.known_roles
and role not in environ["wsgidav.auth.roles"]
):
environ["wsgidav.auth.roles"].append(role)
if len(environ["wsgidav.auth.roles"]) < 1:
environ["wsgidav.auth.roles"].append(self.user_role)
return False
# "wsgidav.auth.roles": null
# "wsgidav.auth.permissions": null
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = [self.anon_role]
if self.anon_role in ("browser", "reader", "editor"):
return False
# "HTTP_USER_AGENT": "Microsoft-WebDAV-MiniRedir/10.0.17134"
if "Microsoft-WebDAV-MiniRedir" in environ.get("HTTP_USER_AGENT", ""):
# TODO: tell users to login via browser at /auth/token first, and then use persistent cookie
# or basic auth with e-mail & access token here?
return True
return True
def basic_auth_user(self, realm, user_name, password, environ):
if environ and environ.get("wsgidav.auth.user_name"):
return True
# We don't have access to a plaintext password (or stored hash)
_logger.debug("Realm: %s" % realm)
_logger.debug("User: %s" % user_name)
# _logger.debug("Pass: %s" % password)
# import json
# _logger.debug("Environ: %s" % json.dumps(environ, indent=2, default=lambda o: repr(o)))
if "Microsoft-WebDAV-MiniRedir" in environ.get("HTTP_USER_AGENT", ""):
# TODO: verify persistent cookie or use basic auth with e-mail & access token?
return True
return False
def supports_http_digest_auth(self):
# We don't have access to a plaintext password (or stored hash)
return False
| 44.333333 | 104 | 0.633611 |
from wsgidav import util
from wsgidav.dc.base_dc import BaseDomainController
from .sessions import get_current_session
__docformat__ = "reStructuredText"
_logger = util.get_module_logger(__name__)
class FirebaseDomainController(BaseDomainController):
known_roles = ("admin", "editor", "reader", "browser", "none")
def __init__(self, wsgidav_app, config):
super().__init__(wsgidav_app, config)
dc_conf = config.get("firebase_dc", {})
self.project_id = dc_conf.get("project_id", None)
self.api_key = dc_conf.get("api_key", None)
self.id_token = dc_conf.get("id_token", "id_token")
self.user_role = dc_conf.get("user_role", "reader")
self.anon_role = dc_conf.get("anon_role", "browser")
def __str__(self):
return f"{self.__class__.__name__}('{self.project_id}')"
def get_domain_realm(self, path_info, environ):
return f"Firebase({self.project_id})"
def require_authentication(self, realm, environ):
# authorization:
# environ["wsgidav.auth.roles"] = None
# environ["wsgidav.auth.permissions"] = None
# "wsgidav.auth.realm": "Firebase(...)"
if not environ:
return True
_logger.debug("Realm: %s" % realm)
# "wsgidav.auth.user_name": "",
if environ.get("wsgidav.auth.user_name"):
_logger.debug("User: %s" % environ.get("wsgidav.auth.user_name"))
return False
# "wsgidav.config": {...}
config = environ.get("wsgidav.config", {})
auth_conf = config.get("http_authenticator", {})
trusted_auth_header = auth_conf.get("trusted_auth_header", None)
if trusted_auth_header and environ.get(trusted_auth_header):
environ["wsgidav.auth.user_name"] = environ.get(trusted_auth_header)
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = [self.user_role]
_logger.debug("Trusted: %s" % environ.get("wsgidav.auth.user_name"))
return False
# "HTTP_COOKIE": "..."
session = get_current_session(environ)
if session.is_user():
environ["wsgidav.auth.user_name"] = session.user_id
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = []
for role in session.get_roles():
if (
role in self.known_roles
and role not in environ["wsgidav.auth.roles"]
):
environ["wsgidav.auth.roles"].append(role)
if len(environ["wsgidav.auth.roles"]) < 1:
environ["wsgidav.auth.roles"].append(self.user_role)
return False
# "wsgidav.auth.roles": null
# "wsgidav.auth.permissions": null
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = [self.anon_role]
if self.anon_role in ("browser", "reader", "editor"):
return False
# "HTTP_USER_AGENT": "Microsoft-WebDAV-MiniRedir/10.0.17134"
if "Microsoft-WebDAV-MiniRedir" in environ.get("HTTP_USER_AGENT", ""):
# TODO: tell users to login via browser at /auth/token first, and then use persistent cookie
# or basic auth with e-mail & access token here?
return True
return True
def basic_auth_user(self, realm, user_name, password, environ):
if environ and environ.get("wsgidav.auth.user_name"):
return True
# We don't have access to a plaintext password (or stored hash)
_logger.debug("Realm: %s" % realm)
_logger.debug("User: %s" % user_name)
if "Microsoft-WebDAV-MiniRedir" in environ.get("HTTP_USER_AGENT", ""):
return True
return False
def supports_http_digest_auth(self):
return False
| true | true |
f72c4c832d99aaf2b05ca354a98a00fc55c755f2 | 1,232 | py | Python | paper_simulation_scripts/run_one_job.py | bsierieb1/SCDCdm_public | 4cd3460a598fad01cb556dc1fb86f63d805ee052 | [
"BSD-3-Clause"
] | 1 | 2021-03-31T10:44:48.000Z | 2021-03-31T10:44:48.000Z | paper_simulation_scripts/run_one_job.py | neurogenomics/scCODA | db610c1bda904f79a8142da767cf8e62d1cd8d32 | [
"BSD-3-Clause"
] | null | null | null | paper_simulation_scripts/run_one_job.py | neurogenomics/scCODA | db610c1bda904f79a8142da767cf8e62d1cd8d32 | [
"BSD-3-Clause"
] | null | null | null | """
This script is executed in each job on the server to run simulation studies on all the parameters that are passed to it
"""
import sys
import ast
import numpy as np
from scdcdm.util import multi_parameter_sampling as mult
# Convert string parameters to lists
cases = ast.literal_eval(sys.argv[1])
print("cases:", cases)
K = ast.literal_eval(sys.argv[2])
print("K:", K)
n_total = ast.literal_eval(sys.argv[3])
print("n_total:", n_total)
n_samples = ast.literal_eval(sys.argv[4])
print("n_samples:", n_samples)
print(sys.argv[5])
b_true = ast.literal_eval(sys.argv[5])
print("b_true:", b_true)
w_true = ast.literal_eval(sys.argv[6])
print("w_true:", w_true)
num_results = ast.literal_eval(sys.argv[7])
print("num_results:", num_results)
n = ast.literal_eval(sys.argv[8])
print("n:", n)
# Run simulation study
p = mult.MultiParamSimulation(cases, K, n_total, n_samples, b_true, w_true, num_results,
baseline_index=4, formula="x_0")
p.simulate()
p.save(path="/home/icb/johannes.ostner/compositional_diff/compositionalDiff-johannes_tests_2/benchmark_results/overall_benchmark/",
filename="result_b_" + str(np.round(b_true, 3)).replace(" ", " ") + "_w_" + str(w_true) + "_round_" + str(n))
| 32.421053 | 131 | 0.719156 | import sys
import ast
import numpy as np
from scdcdm.util import multi_parameter_sampling as mult
cases = ast.literal_eval(sys.argv[1])
print("cases:", cases)
K = ast.literal_eval(sys.argv[2])
print("K:", K)
n_total = ast.literal_eval(sys.argv[3])
print("n_total:", n_total)
n_samples = ast.literal_eval(sys.argv[4])
print("n_samples:", n_samples)
print(sys.argv[5])
b_true = ast.literal_eval(sys.argv[5])
print("b_true:", b_true)
w_true = ast.literal_eval(sys.argv[6])
print("w_true:", w_true)
num_results = ast.literal_eval(sys.argv[7])
print("num_results:", num_results)
n = ast.literal_eval(sys.argv[8])
print("n:", n)
p = mult.MultiParamSimulation(cases, K, n_total, n_samples, b_true, w_true, num_results,
baseline_index=4, formula="x_0")
p.simulate()
p.save(path="/home/icb/johannes.ostner/compositional_diff/compositionalDiff-johannes_tests_2/benchmark_results/overall_benchmark/",
filename="result_b_" + str(np.round(b_true, 3)).replace(" ", " ") + "_w_" + str(w_true) + "_round_" + str(n))
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.