code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup (
name='0-core-client',
version='1.1.0-alpha-4',
description='Zero-OS 0-core client',
long_description=long_description,
url='https://github.com/zero-os/0-core',
author='Muhamad Azmy',
author_email='muhamada@greenitglobe.com',
license='Apache 2.0',
namespaces=['zeroos'],
packages=find_packages(),
install_requires=['redis>=2.10.5'],
)
| 0-core-client | /0-core-client-1.1.0a4.tar.gz/0-core-client-1.1.0a4/setup.py | setup.py |
__import__('pkg_resources').declare_namespace(__name__)
| 0-core-client | /0-core-client-1.1.0a4.tar.gz/0-core-client-1.1.0a4/zeroos/__init__.py | __init__.py |
import redis
import uuid
import json
import textwrap
import shlex
import base64
import signal
import socket
import logging
import time
from . import typchk
DefaultTimeout = 10 # seconds
logger = logging.getLogger('g8core')
class Timeout(Exception):
pass
class JobNotFound(Exception):
pass
class Return:
def __init__(self, payload):
self._payload = payload
@property
def payload(self):
return self._payload
@property
def id(self):
return self._payload['id']
@property
def data(self):
"""
data returned by the process. Only available if process
output data with the correct core level
"""
return self._payload['data']
@property
def level(self):
"""data message level (if any)"""
return self._payload['level']
@property
def starttime(self):
"""timestamp"""
return self._payload['starttime'] / 1000
@property
def time(self):
"""execution time in millisecond"""
return self._payload['time']
@property
def state(self):
"""
exit state
"""
return self._payload['state']
@property
def stdout(self):
streams = self._payload.get('streams', None)
return streams[0] if streams is not None and len(streams) >= 1 else ''
@property
def stderr(self):
streams = self._payload.get('streams', None)
return streams[1] if streams is not None and len(streams) >= 2 else ''
def __repr__(self):
return str(self)
def __str__(self):
tmpl = """\
STATE: {state}
STDOUT:
{stdout}
STDERR:
{stderr}
DATA:
{data}
"""
return textwrap.dedent(tmpl).format(state=self.state, stdout=self.stdout, stderr=self.stderr, data=self.data)
class Response:
def __init__(self, client, id):
self._client = client
self._id = id
self._queue = 'result:{}'.format(id)
@property
def id(self):
return self._id
@property
def exists(self):
r = self._client._redis
flag = '{}:flag'.format(self._queue)
return r.rpoplpush(flag, flag) is not None
def get(self, timeout=None):
if timeout is None:
timeout = self._client.timeout
r = self._client._redis
start = time.time()
maxwait = timeout
while maxwait > 0:
if not self.exists:
raise JobNotFound(self.id)
v = r.brpoplpush(self._queue, self._queue, 10)
if v is not None:
payload = json.loads(v.decode())
r = Return(payload)
logger.debug('%s << %s, stdout="%s", stderr="%s", data="%s"',
self._id, r.state, r.stdout, r.stderr, r.data[:1000])
return r
logger.debug('%s still waiting (%ss)', self._id, int(time.time() - start))
maxwait -= 10
raise Timeout()
class InfoManager:
def __init__(self, client):
self._client = client
def cpu(self):
return self._client.json('info.cpu', {})
def nic(self):
return self._client.json('info.nic', {})
def mem(self):
return self._client.json('info.mem', {})
def disk(self):
return self._client.json('info.disk', {})
def os(self):
return self._client.json('info.os', {})
def port(self):
return self._client.json('info.port', {})
def version(self):
return self._client.json('info.version', {})
class JobManager:
_job_chk = typchk.Checker({
'id': str,
})
_kill_chk = typchk.Checker({
'id': str,
'signal': int,
})
def __init__(self, client):
self._client = client
def list(self, id=None):
"""
List all running jobs
:param id: optional ID for the job to list
"""
args = {'id': id}
self._job_chk.check(args)
return self._client.json('job.list', args)
def kill(self, id, signal=signal.SIGTERM):
"""
Kill a job with given id
:WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable
:param id: job id to kill
"""
args = {
'id': id,
'signal': int(signal),
}
self._kill_chk.check(args)
return self._client.json('job.kill', args)
class ProcessManager:
_process_chk = typchk.Checker({
'pid': int,
})
_kill_chk = typchk.Checker({
'pid': int,
'signal': int,
})
def __init__(self, client):
self._client = client
def list(self, id=None):
"""
List all running processes
:param id: optional PID for the process to list
"""
args = {'pid': id}
self._process_chk.check(args)
return self._client.json('process.list', args)
def kill(self, pid, signal=signal.SIGTERM):
"""
Kill a process with given pid
:WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable
:param pid: PID to kill
"""
args = {
'pid': pid,
'signal': int(signal),
}
self._kill_chk.check(args)
return self._client.json('process.kill', args)
class FilesystemManager:
def __init__(self, client):
self._client = client
def open(self, file, mode='r', perm=0o0644):
"""
Opens a file on the node
:param file: file path to open
:param mode: open mode
:param perm: file permission in octet form
mode:
'r' read only
'w' write only (truncate)
'+' read/write
'x' create if not exist
'a' append
:return: a file descriptor
"""
args = {
'file': file,
'mode': mode,
'perm': perm,
}
return self._client.json('filesystem.open', args)
def exists(self, path):
"""
Check if path exists
:param path: path to file/dir
:return: boolean
"""
args = {
'path': path,
}
return self._client.json('filesystem.exists', args)
def list(self, path):
"""
List all entries in directory
:param path: path to dir
:return: list of director entries
"""
args = {
'path': path,
}
return self._client.json('filesystem.list', args)
def mkdir(self, path):
"""
Make a new directory == mkdir -p path
:param path: path to directory to create
:return:
"""
args = {
'path': path,
}
return self._client.json('filesystem.mkdir', args)
def remove(self, path):
"""
Removes a path (recursively)
:param path: path to remove
:return:
"""
args = {
'path': path,
}
return self._client.json('filesystem.remove', args)
def move(self, path, destination):
"""
Move a path to destination
:param path: source
:param destination: destination
:return:
"""
args = {
'path': path,
'destination': destination,
}
return self._client.json('filesystem.move', args)
def chmod(self, path, mode, recursive=False):
"""
Change file/dir permission
:param path: path of file/dir to change
:param mode: octet mode
:param recursive: apply chmod recursively
:return:
"""
args = {
'path': path,
'mode': mode,
'recursive': recursive,
}
return self._client.json('filesystem.chmod', args)
def chown(self, path, user, group, recursive=False):
"""
Change file/dir owner
:param path: path of file/dir
:param user: user name
:param group: group name
:param recursive: apply chown recursively
:return:
"""
args = {
'path': path,
'user': user,
'group': group,
'recursive': recursive,
}
return self._client.json('filesystem.chown', args)
def read(self, fd):
"""
Read a block from the given file descriptor
:param fd: file descriptor
:return: bytes
"""
args = {
'fd': fd,
}
data = self._client.json('filesystem.read', args)
return base64.decodebytes(data.encode())
def write(self, fd, bytes):
"""
Write a block of bytes to an open file descriptor (that is open with one of the writing modes
:param fd: file descriptor
:param bytes: bytes block to write
:return:
:note: don't overkill the node with large byte chunks, also for large file upload check the upload method.
"""
args = {
'fd': fd,
'block': base64.encodebytes(bytes).decode(),
}
return self._client.json('filesystem.write', args)
def close(self, fd):
"""
Close file
:param fd: file descriptor
:return:
"""
args = {
'fd': fd,
}
return self._client.json('filesystem.close', args)
def upload(self, remote, reader):
"""
Uploads a file
:param remote: remote file name
:param reader: an object that implements the read(size) method (typically a file descriptor)
:return:
"""
fd = self.open(remote, 'w')
while True:
chunk = reader.read(512 * 1024)
if chunk == b'':
break
self.write(fd, chunk)
self.close(fd)
def download(self, remote, writer):
"""
Downloads a file
:param remote: remote file name
:param writer: an object the implements the write(bytes) interface (typical a file descriptor)
:return:
"""
fd = self.open(remote)
while True:
chunk = self.read(fd)
if chunk == b'':
break
writer.write(chunk)
self.close(fd)
def upload_file(self, remote, local):
"""
Uploads a file
:param remote: remote file name
:param local: local file name
:return:
"""
file = open(local, 'rb')
self.upload(remote, file)
def download_file(self, remote, local):
"""
Downloads a file
:param remote: remote file name
:param local: local file name
:return:
"""
file = open(local, 'wb')
self.download(remote, file)
class BaseClient:
_system_chk = typchk.Checker({
'name': str,
'args': [str],
'dir': str,
'stdin': str,
'env': typchk.Or(typchk.Map(str, str), typchk.IsNone()),
})
_bash_chk = typchk.Checker({
'stdin': str,
'script': str,
})
def __init__(self, timeout=None):
if timeout is None:
self.timeout = DefaultTimeout
else:
self.timeout = timeout
self._info = InfoManager(self)
self._job = JobManager(self)
self._process = ProcessManager(self)
self._filesystem = FilesystemManager(self)
self._ip = IPManager(self)
@property
def info(self):
return self._info
@property
def job(self):
return self._job
@property
def process(self):
return self._process
@property
def filesystem(self):
return self._filesystem
@property
def ip(self):
return self._ip
def raw(self, command, arguments, queue=None, max_time=None):
"""
Implements the low level command call, this needs to build the command structure
and push it on the correct queue.
:param command: Command name to execute supported by the node (ex: core.system, info.cpu, etc...)
check documentation for list of built in commands
:param arguments: A dict of required command arguments depends on the command name.
:return: Response object
"""
raise NotImplemented()
def sync(self, command, arguments):
"""
Same as self.raw except it do a response.get() waiting for the command execution to finish and reads the result
:return: Result object
"""
response = self.raw(command, arguments)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('invalid response: %s' % result.state, result)
return result
def json(self, command, arguments):
"""
Same as self.sync except it assumes the returned result is json, and loads the payload of the return object
:Return: Data
"""
result = self.sync(command, arguments)
if result.level != 20:
raise RuntimeError('invalid result level, expecting json(20) got (%d)' % result.level)
return json.loads(result.data)
def ping(self):
"""
Ping a node, checking for it's availability. a Ping should never fail unless the node is not reachable
or not responsive.
:return:
"""
response = self.raw('core.ping', {})
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('invalid response: %s' % result.state)
return json.loads(result.data)
def system(self, command, dir='', stdin='', env=None):
"""
Execute a command
:param command: command to execute (with its arguments) ex: `ls -l /root`
:param dir: CWD of command
:param stdin: Stdin data to feed to the command stdin
:param env: dict with ENV variables that will be exported to the command
:return:
"""
parts = shlex.split(command)
if len(parts) == 0:
raise ValueError('invalid command')
args = {
'name': parts[0],
'args': parts[1:],
'dir': dir,
'stdin': stdin,
'env': env,
}
self._system_chk.check(args)
response = self.raw(command='core.system', arguments=args)
return response
def bash(self, script, stdin=''):
"""
Execute a bash script, or run a process inside a bash shell.
:param script: Script to execute (can be multiline script)
:param stdin: Stdin data to feed to the script
:return:
"""
args = {
'script': script,
'stdin': stdin,
}
self._bash_chk.check(args)
response = self.raw(command='bash', arguments=args)
return response
class ContainerClient(BaseClient):
class ContainerZerotierManager:
def __init__(self, client, container):
self._container = container
self._client = client
def info(self):
return self._client.json('corex.zerotier.info', {'container': self._container})
def list(self):
return self._client.json('corex.zerotier.list', {'container': self._container})
_raw_chk = typchk.Checker({
'container': int,
'command': {
'command': str,
'arguments': typchk.Any(),
'queue': typchk.Or(str, typchk.IsNone()),
'max_time': typchk.Or(int, typchk.IsNone()),
}
})
def __init__(self, client, container):
super().__init__(client.timeout)
self._client = client
self._container = container
self._zerotier = ContainerClient.ContainerZerotierManager(client, container) # not (self) we use core0 client
@property
def container(self):
return self._container
@property
def zerotier(self):
return self._zerotier
def raw(self, command, arguments, queue=None, max_time=None):
"""
Implements the low level command call, this needs to build the command structure
and push it on the correct queue.
:param command: Command name to execute supported by the node (ex: core.system, info.cpu, etc...)
check documentation for list of built in commands
:param arguments: A dict of required command arguments depends on the command name.
:return: Response object
"""
args = {
'container': self._container,
'command': {
'command': command,
'arguments': arguments,
'queue': queue,
'max_time': max_time,
},
}
# check input
self._raw_chk.check(args)
response = self._client.raw('corex.dispatch', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to dispatch command to container: %s' % result.data)
cmd_id = json.loads(result.data)
return self._client.response_for(cmd_id)
class ContainerManager:
_create_chk = typchk.Checker({
'root': str,
'mount': typchk.Or(
typchk.Map(str, str),
typchk.IsNone()
),
'host_network': bool,
'nics': [{
'type': typchk.Enum('default', 'bridge', 'zerotier', 'vlan', 'vxlan'),
'id': typchk.Or(str, typchk.Missing()),
'name': typchk.Or(str, typchk.Missing()),
'hwaddr': typchk.Or(str, typchk.Missing()),
'config': typchk.Or(
typchk.Missing,
{
'dhcp': typchk.Or(bool, typchk.Missing()),
'cidr': typchk.Or(str, typchk.Missing()),
'gateway': typchk.Or(str, typchk.Missing()),
'dns': typchk.Or([str], typchk.Missing()),
}
)
}],
'port': typchk.Or(
typchk.Map(int, int),
typchk.IsNone()
),
'privileged': bool,
'hostname': typchk.Or(
str,
typchk.IsNone()
),
'storage': typchk.Or(str, typchk.IsNone()),
'tags': typchk.Or([str], typchk.IsNone())
})
_terminate_chk = typchk.Checker({
'container': int
})
DefaultNetworking = object()
def __init__(self, client):
self._client = client
def create(self, root_url, mount=None, host_network=False, nics=DefaultNetworking, port=None, hostname=None, privileged=True, storage=None, tags=None):
"""
Creater a new container with the given root flist, mount points and
zerotier id, and connected to the given bridges
:param root_url: The root filesystem flist
:param mount: a dict with {host_source: container_target} mount points.
where host_source directory must exists.
host_source can be a url to a flist to mount.
:param host_network: Specify if the container should share the same network stack as the host.
if True, container creation ignores both zerotier, bridge and ports arguments below. Not
giving errors if provided.
:param nics: Configure the attached nics to the container
each nic object is a dict of the format
{
'type': nic_type # default, bridge, zerotier, vlan, or vxlan (note, vlan and vxlan only supported by ovs)
'id': id # depends on the type, bridge name, zerotier network id, the vlan tag or the vxlan id
'name': name of the nic inside the container (ignored in zerotier type)
'hwaddr': Mac address of nic.
'config': { # config is only honored for bridge, vlan, and vxlan types
'dhcp': bool,
'cidr': static_ip # ip/mask
'gateway': gateway
'dns': [dns]
}
}
:param port: A dict of host_port: container_port pairs (only if default networking is enabled)
Example:
`port={8080: 80, 7000:7000}`
:param hostname: Specific hostname you want to give to the container.
if None it will automatically be set to core-x,
x beeing the ID of the container
:param privileged: If true, container runs in privileged mode.
:param storage: A Url to the ardb storage to use to mount the root flist (or any other mount that requires g8fs)
if not provided, the default one from core0 configuration will be used.
"""
if nics == self.DefaultNetworking:
nics = [{'type': 'default'}]
elif nics is None:
nics = []
args = {
'root': root_url,
'mount': mount,
'host_network': host_network,
'nics': nics,
'port': port,
'hostname': hostname,
'privileged': privileged,
'storage': storage,
'tags': tags,
}
# validate input
self._create_chk.check(args)
response = self._client.raw('corex.create', args)
return response
def list(self):
"""
List running containers
:return: a dict with {container_id: <container info object>}
"""
return self._client.json('corex.list', {})
def find(self, *tags):
"""
Find containers that matches set of tags
:param tags:
:return:
"""
tags = list(map(str, tags))
return self._client.json('corex.find', {'tags': tags})
def terminate(self, container):
"""
Terminate a container given it's id
:param container: container id
:return:
"""
args = {
'container': container,
}
self._terminate_chk.check(args)
response = self._client.raw('corex.terminate', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to terminate container: %s' % result.data)
def client(self, container):
"""
Return a client instance that is bound to that container.
:param container: container id
:return: Client object bound to the specified container id
"""
return ContainerClient(self._client, container)
class IPManager:
class IPBridgeManager:
def __init__(self, client):
self._client = client
def add(self, name, hwaddr=None):
args = {
'name': name,
'hwaddr': hwaddr,
}
return self._client.json("ip.bridge.add", args)
def delete(self, name):
args = {
'name': name,
}
return self._client.json("ip.bridge.del", args)
def addif(self, name, inf):
args = {
'name': name,
'inf': inf,
}
return self._client.json('ip.bridge.addif', args)
def delif(self, name, inf):
args = {
'name': name,
'inf': inf,
}
return self._client.json('ip.bridge.delif', args)
class IPLinkManager:
def __init__(self, client):
self._client = client
def up(self, link):
args = {
'name': link,
}
return self._client.json('ip.link.up', args)
def down(self, link):
args = {
'name': link,
}
return self._client.json('ip.link.down', args)
def name(self, link, name):
args = {
'name': link,
'new': name,
}
return self._client.json('ip.link.name', args)
def list(self):
return self._client.json('ip.link.list', {})
class IPAddrManager:
def __init__(self, client):
self._client = client
def add(self, link, ip):
args = {
'name': link,
'ip': ip,
}
return self._client.json('ip.addr.add', args)
def delete(self, link, ip):
args = {
'name': link,
'ip': ip,
}
return self._client.json('ip.addr.del', args)
def list(self, link):
args = {
'name': link,
}
return self._client.json('ip.addr.list', args)
class IPRouteManager:
def __init__(self, client):
self._client = client
def add(self, dev, dst, gw=None):
args = {
'dev': dev,
'dst': dst,
'gw': gw,
}
return self._client.json('ip.route.add', args)
def delete(self, dev, dst, gw=None):
args = {
'dev': dev,
'dst': dst,
'gw': gw,
}
return self._client.json('ip.route.del', args)
def list(self):
return self._client.json('ip.route.list', {})
def __init__(self, client):
self._client = client
self._bridge = IPManager.IPBridgeManager(client)
self._link = IPManager.IPLinkManager(client)
self._addr = IPManager.IPAddrManager(client)
self._route = IPManager.IPRouteManager(client)
@property
def bridge(self):
return self._bridge
@property
def link(self):
return self._link
@property
def addr(self):
return self._addr
@property
def route(self):
return self._route
class BridgeManager:
_bridge_create_chk = typchk.Checker({
'name': str,
'hwaddr': str,
'network': {
'mode': typchk.Or(typchk.Enum('static', 'dnsmasq'), typchk.IsNone()),
'nat': bool,
'settings': typchk.Map(str, str),
}
})
_bridge_delete_chk = typchk.Checker({
'name': str,
})
def __init__(self, client):
self._client = client
def create(self, name, hwaddr=None, network=None, nat=False, settings={}):
"""
Create a bridge with the given name, hwaddr and networking setup
:param name: name of the bridge (must be unique), 15 characters or less, and not equal to "default".
:param hwaddr: MAC address of the bridge. If none, a one will be created for u
:param network: Networking mode, options are none, static, and dnsmasq
:param nat: If true, SNAT will be enabled on this bridge. (IF and ONLY IF an IP is set on the bridge
via the settings, otherwise flag will be ignored) (the cidr attribute of either static, or dnsmasq modes)
:param settings: Networking setting, depending on the selected mode.
none:
no settings, bridge won't get any ip settings
static:
settings={'cidr': 'ip/net'}
bridge will get assigned the given IP address
dnsmasq:
settings={'cidr': 'ip/net', 'start': 'ip', 'end': 'ip'}
bridge will get assigned the ip in cidr
and each running container that is attached to this IP will get
IP from the start/end range. Netmask of the range is the netmask
part of the provided cidr.
if nat is true, SNAT rules will be automatically added in the firewall.
"""
args = {
'name': name,
'hwaddr': hwaddr,
'network': {
'mode': network,
'nat': nat,
'settings': settings,
}
}
self._bridge_create_chk.check(args)
response = self._client.raw('bridge.create', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to create bridge %s' % result.data)
return json.loads(result.data)
def list(self):
"""
List all available bridges
:return: list of bridge names
"""
response = self._client.raw('bridge.list', {})
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to list bridges: %s' % result.data)
return json.loads(result.data)
def delete(self, bridge):
"""
Delete a bridge by name
:param bridge: bridge name
:return:
"""
args = {
'name': bridge,
}
self._bridge_delete_chk.check(args)
response = self._client.raw('bridge.delete', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to list delete: %s' % result.data)
class DiskManager:
_mktable_chk = typchk.Checker({
'disk': str,
'table_type': typchk.Enum('aix', 'amiga', 'bsd', 'dvh', 'gpt', 'mac', 'msdos', 'pc98', 'sun', 'loop')
})
_mkpart_chk = typchk.Checker({
'disk': str,
'start': typchk.Or(int, str),
'end': typchk.Or(int, str),
'part_type': typchk.Enum('primary', 'logical', 'extended'),
})
_getpart_chk = typchk.Checker({
'disk': str,
'part': str,
})
_rmpart_chk = typchk.Checker({
'disk': str,
'number': int,
})
_mount_chk = typchk.Checker({
'options': str,
'source': str,
'target': str,
})
_umount_chk = typchk.Checker({
'source': str,
})
def __init__(self, client):
self._client = client
def list(self):
"""
List available block devices
"""
response = self._client.raw('disk.list', {})
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to list disks: %s' % result.stderr)
if result.level != 20: # 20 is JSON output.
raise RuntimeError('invalid response type from disk.list command')
data = result.data.strip()
if data:
return json.loads(data)
else:
return {}
def mktable(self, disk, table_type='gpt'):
"""
Make partition table on block device.
:param disk: device name (sda, sdb, etc...)
:param table_type: Partition table type as accepted by parted
"""
args = {
'disk': disk,
'table_type': table_type,
}
self._mktable_chk.check(args)
response = self._client.raw('disk.mktable', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to create table: %s' % result.stderr)
def getinfo(self, disk, part=''):
"""
Get more info about a disk or a disk partition
:param disk: (sda, sdb, etc..)
:param part: (sda1, sdb2, etc...)
:return: a dict with {"blocksize", "start", "size", and "free" sections}
"""
args = {
"disk": disk,
"part": part,
}
self._getpart_chk.check(args)
response = self._client.raw('disk.getinfo', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to get info: %s' % result.data)
if result.level != 20: # 20 is JSON output.
raise RuntimeError('invalid response type from disk.getinfo command')
data = result.data.strip()
if data:
return json.loads(data)
else:
return {}
def mkpart(self, disk, start, end, part_type='primary'):
"""
Make partition on disk
:param disk: device name (sda, sdb, etc...)
:param start: partition start as accepted by parted mkpart
:param end: partition end as accepted by parted mkpart
:param part_type: partition type as accepted by parted mkpart
"""
args = {
'disk': disk,
'start': start,
'end': end,
'part_type': part_type,
}
self._mkpart_chk.check(args)
response = self._client.raw('disk.mkpart', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to create partition: %s' % result.stderr)
def rmpart(self, disk, number):
"""
Remove partion from disk
:param disk: device name (sda, sdb, etc...)
:param number: Partition number (starting from 1)
"""
args = {
'disk': disk,
'number': number,
}
self._rmpart_chk.check(args)
response = self._client.raw('disk.rmpart', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to remove partition: %s' % result.stderr)
def mount(self, source, target, options=[]):
"""
Mount partion on target
:param source: Full partition path like /dev/sda1
:param target: Mount point
:param options: Optional mount options
"""
if len(options) == 0:
options = ['']
args = {
'options': ','.join(options),
'source': source,
'target': target,
}
self._mount_chk.check(args)
response = self._client.raw('disk.mount', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to mount partition: %s' % result.stderr)
def umount(self, source):
"""
Unmount partion
:param source: Full partition path like /dev/sda1
"""
args = {
'source': source,
}
self._umount_chk.check(args)
response = self._client.raw('disk.umount', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to umount partition: %s' % result.stderr)
class BtrfsManager:
_create_chk = typchk.Checker({
'label': str,
'metadata': typchk.Enum("raid0", "raid1", "raid5", "raid6", "raid10", "dup", "single", ""),
'data': typchk.Enum("raid0", "raid1", "raid5", "raid6", "raid10", "dup", "single", ""),
'devices': [str],
'overwrite': bool,
})
_device_chk = typchk.Checker({
'mountpoint': str,
'devices': (str,),
})
_subvol_chk = typchk.Checker({
'path': str,
})
_subvol_quota_chk = typchk.Checker({
'path': str,
'limit': str,
})
_subvol_snapshot_chk = typchk.Checker({
'source': str,
'destination': str,
'read_only': bool,
})
def __init__(self, client):
self._client = client
def list(self):
"""
List all btrfs filesystem
"""
return self._client.json('btrfs.list', {})
def info(self, mountpoint):
"""
Get btrfs fs info
"""
return self._client.json('btrfs.info', {'mountpoint': mountpoint})
def create(self, label, devices, metadata_profile="", data_profile="", overwrite=False):
"""
Create a btrfs filesystem with the given label, devices, and profiles
:param label: name/label
:param devices : array of devices (/dev/sda1, etc...)
:metadata_profile: raid0, raid1, raid5, raid6, raid10, dup or single
:data_profile: same as metadata profile
:overwrite: force creation of the filesystem. Overwrite any existing filesystem
"""
args = {
'label': label,
'metadata': metadata_profile,
'data': data_profile,
'devices': devices,
'overwrite': overwrite
}
self._create_chk.check(args)
self._client.sync('btrfs.create', args)
def device_add(self, mountpoint, *device):
"""
Add one or more devices to btrfs filesystem mounted under `mountpoint`
:param mountpoint: mount point of the btrfs system
:param devices: one ore more devices to add
:return:
"""
if len(device) == 0:
return
args = {
'mountpoint': mountpoint,
'devices': device,
}
self._device_chk.check(args)
self._client.sync('btrfs.device_add', args)
def device_remove(self, mountpoint, *device):
"""
Remove one or more devices from btrfs filesystem mounted under `mountpoint`
:param mountpoint: mount point of the btrfs system
:param devices: one ore more devices to remove
:return:
"""
if len(device) == 0:
return
args = {
'mountpoint': mountpoint,
'devices': device,
}
self._device_chk.check(args)
self._client.sync('btrfs.device_remove', args)
def subvol_create(self, path):
"""
Create a btrfs subvolume in the specified path
:param path: path to create
"""
args = {
'path': path
}
self._subvol_chk.check(args)
self._client.sync('btrfs.subvol_create', args)
def subvol_list(self, path):
"""
List a btrfs subvolume in the specified path
:param path: path to be listed
"""
return self._client.json('btrfs.subvol_list', {
'path': path
})
def subvol_delete(self, path):
"""
Delete a btrfs subvolume in the specified path
:param path: path to delete
"""
args = {
'path': path
}
self._subvol_chk.check(args)
self._client.sync('btrfs.subvol_delete', args)
def subvol_quota(self, path, limit):
"""
Apply a quota to a btrfs subvolume in the specified path
:param path: path to apply the quota for (it has to be the path of the subvol)
:param limit: the limit to Apply
"""
args = {
'path': path,
'limit': limit,
}
self._subvol_quota_chk.check(args)
self._client.sync('btrfs.subvol_quota', args)
def subvol_snapshot(self, source, destination, read_only=False):
"""
Take a snapshot
:param source: source path of subvol
:param destination: destination path of snapshot
:param read_only: Set read-only on the snapshot
:return:
"""
args = {
"source": source,
"destination": destination,
"read_only": read_only,
}
self._subvol_snapshot_chk.check(args)
self._client.sync('btrfs.subvol_snapshot', args)
class ZerotierManager:
_network_chk = typchk.Checker({
'network': str,
})
def __init__(self, client):
self._client = client
def join(self, network):
"""
Join a zerotier network
:param network: network id to join
:return:
"""
args = {'network': network}
self._network_chk.check(args)
response = self._client.raw('zerotier.join', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to join zerotier network: %s', result.stderr)
def leave(self, network):
"""
Leave a zerotier network
:param network: network id to leave
:return:
"""
args = {'network': network}
self._network_chk.check(args)
response = self._client.raw('zerotier.leave', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to leave zerotier network: %s', result.stderr)
def list(self):
"""
List joined zerotier networks
:return: list of joined networks with their info
"""
return self._client.json('zerotier.list', {})
def info(self):
"""
Display zerotier status info
:return: dict of zerotier statusinfo
"""
return self._client.json('zerotier.info', {})
class KvmManager:
_iotune_dict = {
'totalbytessecset': bool,
'totalbytessec': int,
'readbytessecset': bool,
'readbytessec': int,
'writebytessecset': bool,
'writebytessec': int,
'totaliopssecset': bool,
'totaliopssec': int,
'readiopssecset': bool,
'readiopssec': int,
'writeiopssecset': bool,
'writeiopssec': int,
'totalbytessecmaxset': bool,
'totalbytessecmax': int,
'readbytessecmaxset': bool,
'readbytessecmax': int,
'writebytessecmaxset': bool,
'writebytessecmax': int,
'totaliopssecmaxset': bool,
'totaliopssecmax': int,
'readiopssecmaxset': bool,
'readiopssecmax': int,
'writeiopssecmaxset': bool,
'writeiopssecmax': int,
'totalbytessecmaxlengthset': bool,
'totalbytessecmaxlength': int,
'readbytessecmaxlengthset': bool,
'readbytessecmaxlength': int,
'writebytessecmaxlengthset': bool,
'writebytessecmaxlength': int,
'totaliopssecmaxlengthset': bool,
'totaliopssecmaxlength': int,
'readiopssecmaxlengthset': bool,
'readiopssecmaxlength': int,
'writeiopssecmaxlengthset': bool,
'writeiopssecmaxlength': int,
'sizeiopssecset': bool,
'sizeiopssec': int,
'groupnameset': bool,
'groupname': str,
}
_media_dict = {
'type': typchk.Or(
typchk.Enum('disk', 'cdrom'),
typchk.Missing()
),
'url': str,
'iotune': typchk.Or(
_iotune_dict,
typchk.Missing()
)
}
_create_chk = typchk.Checker({
'name': str,
'media': typchk.Length([_media_dict], 1),
'cpu': int,
'memory': int,
'nics': [{
'type': typchk.Enum('default', 'bridge', 'vxlan', 'vlan'),
'id': typchk.Or(str, typchk.Missing()),
'hwaddr': typchk.Or(str, typchk.Missing()),
}],
'port': typchk.Or(
typchk.Map(int, int),
typchk.IsNone()
),
})
_domain_action_chk = typchk.Checker({
'uuid': str,
})
_man_disk_action_chk = typchk.Checker({
'uuid': str,
'media': _media_dict,
})
_man_nic_action_chk = typchk.Checker({
'uuid': str,
'type': typchk.Enum('default', 'bridge', 'vxlan', 'vlan'),
'id': typchk.Or(str, typchk.Missing()),
'hwaddr': typchk.Or(str, typchk.Missing()),
})
_migrate_action_chk = typchk.Checker({
'uuid': str,
'desturi': str,
})
_limit_disk_io_dict = {
'uuid': str,
'media': _media_dict,
}
_limit_disk_io_dict.update(_iotune_dict)
_limit_disk_io_action_chk = typchk.Checker(_limit_disk_io_dict)
def __init__(self, client):
self._client = client
def create(self, name, media, cpu=2, memory=512, nics=None, port=None):
"""
:param name: Name of the kvm domain
:param media: array of media objects to attach to the machine, where the first object is the boot device
each media object is a dict of {url, type} where type can be one of 'disk', or 'cdrom', or empty (default to disk)
example: [{'url': 'nbd+unix:///test?socket=/tmp/ndb.socket'}, {'type': 'cdrom': '/somefile.iso'}
:param cpu: number of vcpu cores
:param memory: memory in MiB
:param port: A dict of host_port: container_port pairs
Example:
`port={8080: 80, 7000:7000}`
Only supported if default network is used
:param nics: Configure the attached nics to the container
each nic object is a dict of the format
{
'type': nic_type # default, bridge, vlan, or vxlan (note, vlan and vxlan only supported by ovs)
'id': id # depends on the type, bridge name (bridge type) zerotier network id (zertier type), the vlan tag or the vxlan id
}
:return: uuid of the virtual machine
"""
if nics is None:
nics = []
args = {
'name': name,
'media': media,
'cpu': cpu,
'memory': memory,
'nics': nics,
'port': port,
}
self._create_chk.check(args)
return self._client.sync('kvm.create', args)
def destroy(self, uuid):
"""
Destroy a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return:
"""
args = {
'uuid': uuid,
}
self._domain_action_chk.check(args)
self._client.sync('kvm.destroy', args)
def shutdown(self, uuid):
"""
Shutdown a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return:
"""
args = {
'uuid': uuid,
}
self._domain_action_chk.check(args)
self._client.sync('kvm.shutdown', args)
def reboot(self, uuid):
"""
Reboot a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return:
"""
args = {
'uuid': uuid,
}
self._domain_action_chk.check(args)
self._client.sync('kvm.reboot', args)
def reset(self, uuid):
"""
Reset (Force reboot) a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return:
"""
args = {
'uuid': uuid,
}
self._domain_action_chk.check(args)
self._client.sync('kvm.reset', args)
def pause(self, uuid):
"""
Pause a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return:
"""
args = {
'uuid': uuid,
}
self._domain_action_chk.check(args)
self._client.sync('kvm.pause', args)
def resume(self, uuid):
"""
Resume a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return:
"""
args = {
'uuid': uuid,
}
self._domain_action_chk.check(args)
self._client.sync('kvm.resume', args)
def info(self, uuid):
"""
Get info about a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return:
"""
args = {
'uuid': uuid,
}
self._domain_action_chk.check(args)
return self._client.json('kvm.info', args)
def infops(self, uuid):
"""
Get info per second about a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return:
"""
args = {
'uuid': uuid,
}
self._domain_action_chk.check(args)
return self._client.json('kvm.infops', args)
def attach_disk(self, uuid, media):
"""
Attach a disk to a machine
:param uuid: uuid of the kvm container (same as the used in create)
:param media: the media object to attach to the machine
media object is a dict of {url, and type} where type can be one of 'disk', or 'cdrom', or empty (default to disk)
examples: {'url': 'nbd+unix:///test?socket=/tmp/ndb.socket'}, {'type': 'cdrom': '/somefile.iso'}
:return:
"""
args = {
'uuid': uuid,
'media': media,
}
self._man_disk_action_chk.check(args)
self._client.sync('kvm.attach_disk', args)
def detach_disk(self, uuid, media):
"""
Detach a disk from a machine
:param uuid: uuid of the kvm container (same as the used in create)
:param media: the media object to attach to the machine
media object is a dict of {url, and type} where type can be one of 'disk', or 'cdrom', or empty (default to disk)
examples: {'url': 'nbd+unix:///test?socket=/tmp/ndb.socket'}, {'type': 'cdrom': '/somefile.iso'}
:return:
"""
args = {
'uuid': uuid,
'media': media,
}
self._man_disk_action_chk.check(args)
self._client.sync('kvm.detach_disk', args)
def add_nic(self, uuid, type, id=None, hwaddr=None):
"""
Add a nic to a machine
:param uuid: uuid of the kvm container (same as the used in create)
:param type: nic_type # default, bridge, vlan, or vxlan (note, vlan and vxlan only supported by ovs)
param id: id # depends on the type, bridge name (bridge type) zerotier network id (zertier type), the vlan tag or the vxlan id
param hwaddr: the hardware address of the nic
:return:
"""
args = {
'uuid': uuid,
'type': type,
'id': id,
'hwaddr': hwaddr,
}
self._man_nic_action_chk.check(args)
return self._client.json('kvm.add_nic', args)
def remove_nic(self, uuid, type, id=None, hwaddr=None):
"""
Remove a nic from a machine
:param uuid: uuid of the kvm container (same as the used in create)
:param type: nic_type # default, bridge, vlan, or vxlan (note, vlan and vxlan only supported by ovs)
param id: id # depends on the type, bridge name (bridge type) zerotier network id (zertier type), the vlan tag or the vxlan id
param hwaddr: the hardware address of the nic
:return:
"""
args = {
'uuid': uuid,
'type': type,
'id': id,
'hwaddr': hwaddr,
}
self._man_nic_action_chk.check(args)
return self._client.json('kvm.remove_nic', args)
def limit_disk_io(self, uuid, media, totalbytessecset=False, totalbytessec=0, readbytessecset=False, readbytessec=0, writebytessecset=False,
writebytessec=0, totaliopssecset=False, totaliopssec=0, readiopssecset=False, readiopssec=0, writeiopssecset=False, writeiopssec=0,
totalbytessecmaxset=False, totalbytessecmax=0, readbytessecmaxset=False, readbytessecmax=0, writebytessecmaxset=False, writebytessecmax=0,
totaliopssecmaxset=False, totaliopssecmax=0, readiopssecmaxset=False, readiopssecmax=0, writeiopssecmaxset=False, writeiopssecmax=0,
totalbytessecmaxlengthset=False, totalbytessecmaxlength=0, readbytessecmaxlengthset=False, readbytessecmaxlength=0,
writebytessecmaxlengthset=False, writebytessecmaxlength=0, totaliopssecmaxlengthset=False, totaliopssecmaxlength=0,
readiopssecmaxlengthset=False, readiopssecmaxlength=0, writeiopssecmaxlengthset=False, writeiopssecmaxlength=0, sizeiopssecset=False,
sizeiopssec=0, groupnameset=False, groupname=''):
"""
Remove a nic from a machine
:param uuid: uuid of the kvm container (same as the used in create)
:param media: the media to limit the diskio
:return:
"""
args = {
'uuid': uuid,
'media': media,
'totalbytessecset': totalbytessecset,
'totalbytessec': totalbytessec,
'readbytessecset': readbytessecset,
'readbytessec': readbytessec,
'writebytessecset': writebytessecset,
'writebytessec': writebytessec,
'totaliopssecset': totaliopssecset,
'totaliopssec': totaliopssec,
'readiopssecset': readiopssecset,
'readiopssec': readiopssec,
'writeiopssecset': writeiopssecset,
'writeiopssec': writeiopssec,
'totalbytessecmaxset': totalbytessecmaxset,
'totalbytessecmax': totalbytessecmax,
'readbytessecmaxset': readbytessecmaxset,
'readbytessecmax': readbytessecmax,
'writebytessecmaxset': writebytessecmaxset,
'writebytessecmax': writebytessecmax,
'totaliopssecmaxset': totaliopssecmaxset,
'totaliopssecmax': totaliopssecmax,
'readiopssecmaxset': readiopssecmaxset,
'readiopssecmax': readiopssecmax,
'writeiopssecmaxset': writeiopssecmaxset,
'writeiopssecmax': writeiopssecmax,
'totalbytessecmaxlengthset': totalbytessecmaxlengthset,
'totalbytessecmaxlength': totalbytessecmaxlength,
'readbytessecmaxlengthset': readbytessecmaxlengthset,
'readbytessecmaxlength': readbytessecmaxlength,
'writebytessecmaxlengthset': writebytessecmaxlengthset,
'writebytessecmaxlength': writebytessecmaxlength,
'totaliopssecmaxlengthset': totaliopssecmaxlengthset,
'totaliopssecmaxlength': totaliopssecmaxlength,
'readiopssecmaxlengthset': readiopssecmaxlengthset,
'readiopssecmaxlength': readiopssecmaxlength,
'writeiopssecmaxlengthset': writeiopssecmaxlengthset,
'writeiopssecmaxlength': writeiopssecmaxlength,
'sizeiopssecset': sizeiopssecset,
'sizeiopssec': sizeiopssec,
'groupnameset': groupnameset,
'groupname': groupname,
}
self._limit_disk_io_action_chk.check(args)
self._client.sync('kvm.limit_disk_io', args)
def migrate(self, uuid, desturi):
"""
Migrate a vm to another node
:param uuid: uuid of the kvm container (same as the used in create)
:param desturi: the uri of the destination node
:return:
"""
args = {
'uuid': uuid,
'desturi': desturi,
}
self._migrate_action_chk.check(args)
self._client.sync('kvm.migrate', args)
def list(self):
"""
List configured domains
:return:
"""
return self._client.json('kvm.list', {})
class Logger:
_level_chk = typchk.Checker({
'level': typchk.Enum("CRITICAL", "ERROR", "WARNING", "NOTICE", "INFO", "DEBUG"),
})
def __init__(self, client):
self._client = client
def set_level(self, level):
"""
Set the log level of the g8os
:param level: the level to be set can be one of ("CRITICAL", "ERROR", "WARNING", "NOTICE", "INFO", "DEBUG")
"""
args = {
'level': level,
}
self._level_chk.check(args)
return self._client.json('logger.set_level', args)
def reopen(self):
"""
Reopen log file
"""
return self._client.json('logger.reopen', {})
class Nft:
_port_chk = typchk.Checker({
'port': int,
'interface': typchk.Or(str, typchk.Missing()),
'subnet': typchk.Or(str, typchk.Missing()),
})
def __init__(self, client):
self._client = client
def open_port(self, port, interface=None, subnet=None):
"""
open port
:param port: then port number
:param interface: an optional interface to open the port for
:param subnet: an optional subnet to open the port for
"""
args = {
'port': port,
'interface': interface,
'subnet': subnet,
}
self._port_chk.check(args)
return self._client.json('nft.open_port', args)
def drop_port(self, port, interface=None, subnet=None):
"""
close an opened port (takes the same parameters passed in open)
:param port: then port number
:param interface: an optional interface to close the port for
:param subnet: an optional subnet to close the port for
"""
args = {
'port': port,
'interface': interface,
'subnet': subnet,
}
self._port_chk.check(args)
return self._client.json('nft.drop_port', args)
class Config:
def __init__(self, client):
self._client = client
def get(self):
"""
Get the config of g8os
"""
return self._client.json('config.get', {})
class Experimental:
def __init__(self, client):
pass
class Client(BaseClient):
def __init__(self, host, port=6379, password="", db=0, ssl=True, timeout=None, testConnectionAttempts=3):
super().__init__(timeout=timeout)
socket_timeout = (timeout + 5) if timeout else 15
self._redis = redis.Redis(host=host, port=port, password=password, db=db, ssl=ssl,
socket_timeout=socket_timeout,
socket_keepalive=True, socket_keepalive_options={
socket.TCP_KEEPINTVL: 1,
socket.TCP_KEEPCNT: 10
})
self._container_manager = ContainerManager(self)
self._bridge_manager = BridgeManager(self)
self._disk_manager = DiskManager(self)
self._btrfs_manager = BtrfsManager(self)
self._zerotier = ZerotierManager(self)
self._experimntal = Experimental(self)
self._kvm = KvmManager(self)
self._logger = Logger(self)
self._nft = Nft(self)
self._config = Config(self)
if testConnectionAttempts:
for _ in range(testConnectionAttempts):
try:
self.ping()
except:
pass
else:
return
raise RuntimeError("Could not connect to remote host %s" % host)
@property
def experimental(self):
return self._experimntal
@property
def container(self):
return self._container_manager
@property
def bridge(self):
return self._bridge_manager
@property
def disk(self):
return self._disk_manager
@property
def btrfs(self):
return self._btrfs_manager
@property
def zerotier(self):
return self._zerotier
@property
def kvm(self):
return self._kvm
@property
def logger(self):
return self._logger
@property
def nft(self):
return self._nft
@property
def config(self):
return self._config
def raw(self, command, arguments, queue=None, max_time=None):
"""
Implements the low level command call, this needs to build the command structure
and push it on the correct queue.
:param command: Command name to execute supported by the node (ex: core.system, info.cpu, etc...)
check documentation for list of built in commands
:param arguments: A dict of required command arguments depends on the command name.
:return: Response object
"""
id = str(uuid.uuid4())
payload = {
'id': id,
'command': command,
'arguments': arguments,
'queue': queue,
'max_time': max_time,
}
flag = 'result:{}:flag'.format(id)
self._redis.rpush('core:default', json.dumps(payload))
if self._redis.brpoplpush(flag, flag, DefaultTimeout) is None:
Timeout('failed to queue job {}'.format(id))
logger.debug('%s >> g8core.%s(%s)', id, command, ', '.join(("%s=%s" % (k, v) for k, v in arguments.items())))
return Response(self, id)
def response_for(self, id):
return Response(self, id)
| 0-core-client | /0-core-client-1.1.0a4.tar.gz/0-core-client-1.1.0a4/zeroos/core0/client/client.py | client.py |
missing = object()
def primitive(typ):
return typ in [str, int, float, bool]
class CheckerException(BaseException):
pass
class Tracker(BaseException):
def __init__(self, base):
self._base = base
self._reason = None
self._branches = []
@property
def branches(self):
return self._branches
def copy(self):
l = self._base.copy()
t = Tracker(l)
t._reason = self._reason
return t
def push(self, s):
t = self.copy()
t._base.append(str(s))
return t
def pop(self):
t = self.copy()
t._base.pop()
return t
def reason(self, reason):
self._reason = reason
return self
def branch(self, tracker):
t = tracker.copy()
self._branches.append(t)
def __str__(self):
u = "/".join(self._base)
if self._reason is not None:
u = '[{}] at -> {}'.format(self._reason, u)
for branch in self.branches:
u += '\n -> {}'.format(branch)
return u
def __repr__(self):
return str(self)
class Option:
def __init__(self):
raise NotImplementedError()
def check(self, object, t):
raise NotImplementedError()
class Or(Option):
def __init__(self, *types):
self._checkers = []
for typ in types:
self._checkers.append(Checker(typ))
def check(self, object, t):
bt = t.copy()
for chk in self._checkers:
try:
chk.check(object, bt)
return
except Tracker as tx:
t.branch(tx)
raise t.reason('all branches failed')
class IsNone(Option):
def __init__(self):
pass
def check(self, object, t):
if object is not None:
raise t.reason('is not none')
class Missing(Option):
def __init__(self):
pass
def check(self, object, t):
if object != missing:
raise t.reason('is not missing')
class Any(Option):
def __init__(self):
pass
def check(self, object, t):
return
class Length(Option):
def __init__(self, typ, min=None, max=None):
self._checker = Checker(typ)
if min is None and max is None:
raise ValueError("you have to pass wither min or max to the length type checker")
self._min = min
self._max = max
def check(self, object, t):
self._checker.check(object, t)
if self._min is not None and len(object) < self._min:
raise t.reason('invalid length, expecting more than or equal {} got {}'.format(self._min, len(object)))
if self._max is not None and len(object) > self._max:
raise t.reason('invalid length, expecting less than or equal {} got {}'.format(self._max, len(object)))
class Map(Option):
def __init__(self, key_type, value_type):
self._key = Checker(key_type)
self._value = Checker(value_type)
def check(self, object, t):
if not isinstance(object, dict):
raise t.reason('expecting a dict, got {}'.format(type(object)))
for k, v in object.items():
tx = t.push(k)
self._key.check(k, tx)
tv = t.push('{}[value]'.format(k))
self._value.check(v, tv)
class Enum(Option):
def __init__(self, *valid):
self._valid = valid
def check(self, object, t):
if not isinstance(object, str):
raise t.reason('expecting string, got {}'.format(type(object)))
if object not in self._valid:
raise t.reason('value "{}" not in enum'.format(object))
class Checker:
"""
Build a type checker to check method inputs
A Checker takes a type definition as following
c = Checker(<type-def>)
then use c to check inputs as
valid = c.check(value)
type-def:
- primitive types (str, bool, int, float)
- composite types ([str], [int], etc...)
- dicts types ({'name': str, 'age': float, etc...})
To build a more complex type-def u can use the available Options in typechk module
- Or(type-def, type-def, ...)
- Missing() (Only make sense in dict types)
- IsNone() (accept None value)
Example of type definition
A dict object, with the following attributes
- `name` of type string
- optional `age` which can be int, or float
- A list of children each has
- string name
- float age
c = Checker({
'name': str,
'age': Or(int, float, Missing()),
'children': [{'name': str, 'age': float}]
})
c.check({'name': 'azmy', 'age': 34, children:[]}) # passes
c.check({'name': 'azmy', children:[]}) # passes
c.check({'age': 34, children:[]}) # does not pass
c.check({'name': 'azmy', children:[{'name': 'yahia', 'age': 4.0}]}) # passes
c.check({'name': 'azmy', children:[{'name': 'yahia', 'age': 4.0}, {'name': 'yassine'}]}) # does not pass
"""
def __init__(self, tyepdef):
self._typ = tyepdef
def check(self, object, tracker=None):
if tracker is None:
tracker = Tracker([]).push('/')
return self._check(self._typ, object, tracker)
def _check_list(self, typ, obj_list, t):
for i, elem in enumerate(obj_list):
tx = t.push('[{}]'.format(i))
self._check(typ, elem, tx)
def _check_dict(self, typ, obj_dict, t):
given = []
for name, value in obj_dict.items():
tx = t.push(name)
if name not in typ:
raise tx.reason('unknown key "{}"'.format(name))
given.append(name)
attr_type = typ[name]
self._check(attr_type, value, tx)
if len(given) == len(typ):
return
type_keys = list(typ.keys())
for key in given:
type_keys.remove(key)
for required in type_keys:
tx = t.push(required)
self._check(typ[required], missing, tx)
def _check(self, typ, object, t):
if isinstance(typ, Option):
return typ.check(object, t)
atyp = type(object)
if primitive(atyp) and atyp != typ:
raise t.reason('invalid type, expecting {}'.format(typ))
if isinstance(typ, list):
if atyp != list:
raise t.reason('expecting a list')
self._check_list(typ[0], object, t)
if isinstance(typ, tuple):
if atyp != tuple:
raise t.reason('expecting a tuple')
self._check_list(typ[0], object, t)
elif isinstance(typ, dict):
if atyp != dict:
raise t.reason('expecting a dict')
self._check_dict(typ, object, t)
| 0-core-client | /0-core-client-1.1.0a4.tar.gz/0-core-client-1.1.0a4/zeroos/core0/client/typchk.py | typchk.py |
from .client import Client
| 0-core-client | /0-core-client-1.1.0a4.tar.gz/0-core-client-1.1.0a4/zeroos/core0/client/__init__.py | __init__.py |
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='0-orchestrator',
version='1.1.0-alpha-7',
description='Zero-OS Orchestrator',
long_description=long_description,
url='https://github.com/g8os/grid',
author='Christophe de Carvalho',
author_email='christophe@gig.tech',
license='Apache 2.0',
packages=find_packages(),
include_package_data=True,
package_data={
'zeroos.orchestrator.sal.templates': ['*.conf', 'dhcp', 'dashboards/*']
},
namespace_packages=['zeroos'],
install_requires=['python-dateutil', 'Jinja2'],
)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/setup.py | setup.py |
__import__('pkg_resources').declare_namespace(__name__)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/__init__.py | __init__.py |
def get_configuration_and_service(ays_repo):
services = ays_repo.servicesFind(actor='configuration')
if len(services) > 1:
raise RuntimeError('Multiple configuration services found')
service = services[0] if services else None
configuration = service.model.data.to_dict()['configurations'] if service else []
return {conf['key']: conf['value'] for conf in configuration}, service
def get_configuration(ays_repo):
configs, _ = get_configuration_and_service(ays_repo)
return configs
def refresh_jwt_token(token):
import requests
import time
headers = {'Authorization': 'bearer %s' % token}
params = {'validity': '3600'}
resp = requests.get('https://itsyou.online/v1/oauth/jwt/refresh', headers=headers, params=params)
resp.raise_for_status()
return resp.content.decode()
def get_jwt_token(ays_repo):
import jose
import jose.jwt
import requests
import time
configs, service = get_configuration_and_service(ays_repo)
jwt_token = configs.get('jwt-token', '')
jwt_key = configs.get('jwt-key')
if not jwt_token:
return jwt_token
try:
token = jose.jwt.decode(jwt_token, jwt_key)
if token['exp'] < time.time() - 240:
jwt_token = refresh_jwt_token(jwt_token)
if token['exp'] > time.time() + 3600:
raise RuntimeError('Invalid jwt-token expiration time is too long should be less than 3600 sec')
except jose.exceptions.ExpiredSignatureError:
jwt_token = refresh_jwt_token(jwt_token)
except Exception:
raise RuntimeError('Invalid jwt-token and jwt-key combination')
for config in service.model.data.configurations:
if config.key == 'jwt-token':
config.value = jwt_token
break
service.saveAll()
return jwt_token
def get_jwt_token_from_job(job):
if 'token' in job.context:
return job.context['token']
return get_jwt_token(job.service.aysrepo)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/configuration.py | configuration.py |
"""
Auto-generated class for Cluster
"""
from .EnumClusterDriveType import EnumClusterDriveType
from .EnumClusterStatus import EnumClusterStatus
from .StorageServer import StorageServer
from . import client_support
class Cluster(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(dataStorage, driveType, label, metadataStorage, nodes, status):
"""
:type dataStorage: list[StorageServer]
:type driveType: EnumClusterDriveType
:type label: str
:type metadataStorage: list[StorageServer]
:type nodes: list[str]
:type status: EnumClusterStatus
:rtype: Cluster
"""
return Cluster(
dataStorage=dataStorage,
driveType=driveType,
label=label,
metadataStorage=metadataStorage,
nodes=nodes,
status=status,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'Cluster'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'dataStorage'
val = data.get(property_name)
if val is not None:
datatypes = [StorageServer]
try:
self.dataStorage = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'driveType'
val = data.get(property_name)
if val is not None:
datatypes = [EnumClusterDriveType]
try:
self.driveType = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'label'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.label = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'metadataStorage'
val = data.get(property_name)
if val is not None:
datatypes = [StorageServer]
try:
self.metadataStorage = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'nodes'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.nodes = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [EnumClusterStatus]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/Cluster.py | Cluster.py |
from enum import Enum
class EnumClusterCreateDriveType(Enum):
nvme = "nvme"
ssd = "ssd"
hdd = "hdd"
archive = "archive"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/EnumClusterCreateDriveType.py | EnumClusterCreateDriveType.py |
from enum import Enum
class EnumBridgeCreateNetworkMode(Enum):
none = "none"
static = "static"
dnsmasq = "dnsmasq"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/EnumBridgeCreateNetworkMode.py | EnumBridgeCreateNetworkMode.py |
from enum import Enum
class EnumContainerNICType(Enum):
zerotier = "zerotier"
vxlan = "vxlan"
vlan = "vlan"
default = "default"
bridge = "bridge"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/EnumContainerNICType.py | EnumContainerNICType.py |
from enum import Enum
class EnumStoragePoolDeviceStatus(Enum):
healthy = "healthy"
removing = "removing"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/EnumStoragePoolDeviceStatus.py | EnumStoragePoolDeviceStatus.py |
"""
Auto-generated class for FilesystemCreate
"""
from . import client_support
class FilesystemCreate(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(name, quota, readOnly):
"""
:type name: str
:type quota: int
:type readOnly: bool
:rtype: FilesystemCreate
"""
return FilesystemCreate(
name=name,
quota=quota,
readOnly=readOnly,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'FilesystemCreate'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'name'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.name = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'quota'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.quota = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'readOnly'
val = data.get(property_name)
if val is not None:
datatypes = [bool]
try:
self.readOnly = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/FilesystemCreate.py | FilesystemCreate.py |
"""
Auto-generated class for ProcessSignal
"""
from . import client_support
class ProcessSignal(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(signal):
"""
:type signal: int
:rtype: ProcessSignal
"""
return ProcessSignal(
signal=signal,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'ProcessSignal'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'signal'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.signal = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/ProcessSignal.py | ProcessSignal.py |
"""
Auto-generated class for VM
"""
from .EnumVMStatus import EnumVMStatus
from .NicLink import NicLink
from .VDiskLink import VDiskLink
from . import client_support
class VM(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(cpu, disks, id, memory, nics, status, vnc):
"""
:type cpu: int
:type disks: list[VDiskLink]
:type id: str
:type memory: int
:type nics: list[NicLink]
:type status: EnumVMStatus
:type vnc: int
:rtype: VM
"""
return VM(
cpu=cpu,
disks=disks,
id=id,
memory=memory,
nics=nics,
status=status,
vnc=vnc,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'VM'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'cpu'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.cpu = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'disks'
val = data.get(property_name)
if val is not None:
datatypes = [VDiskLink]
try:
self.disks = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'id'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.id = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'memory'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.memory = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'nics'
val = data.get(property_name)
if val is not None:
datatypes = [NicLink]
try:
self.nics = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [EnumVMStatus]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'vnc'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.vnc = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/VM.py | VM.py |
"""
Auto-generated class for HealthCheck
"""
from . import client_support
class HealthCheck(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(id, message, name, resource, status):
"""
:type id: str
:type message: str
:type name: str
:type resource: str
:type status: str
:rtype: HealthCheck
"""
return HealthCheck(
id=id,
message=message,
name=name,
resource=resource,
status=status,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'HealthCheck'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'id'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.id = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'message'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.message = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'name'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.name = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'resource'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.resource = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/HealthCheck.py | HealthCheck.py |
from enum import Enum
class EnumStoragePoolCreateDataProfile(Enum):
raid0 = "raid0"
raid1 = "raid1"
raid5 = "raid5"
raid6 = "raid6"
raid10 = "raid10"
dup = "dup"
single = "single"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/EnumStoragePoolCreateDataProfile.py | EnumStoragePoolCreateDataProfile.py |
from enum import Enum
class EnumStoragePoolDataProfile(Enum):
raid0 = "raid0"
raid1 = "raid1"
raid5 = "raid5"
raid6 = "raid6"
raid10 = "raid10"
dup = "dup"
single = "single"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/EnumStoragePoolDataProfile.py | EnumStoragePoolDataProfile.py |
"""
Auto-generated class for StoragePool
"""
from .EnumStoragePoolDataProfile import EnumStoragePoolDataProfile
from .EnumStoragePoolMetadataProfile import EnumStoragePoolMetadataProfile
from .EnumStoragePoolStatus import EnumStoragePoolStatus
from . import client_support
class StoragePool(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(capacity, dataProfile, metadataProfile, mountpoint, name, status, totalCapacity):
"""
:type capacity: int
:type dataProfile: EnumStoragePoolDataProfile
:type metadataProfile: EnumStoragePoolMetadataProfile
:type mountpoint: str
:type name: str
:type status: EnumStoragePoolStatus
:type totalCapacity: int
:rtype: StoragePool
"""
return StoragePool(
capacity=capacity,
dataProfile=dataProfile,
metadataProfile=metadataProfile,
mountpoint=mountpoint,
name=name,
status=status,
totalCapacity=totalCapacity,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'StoragePool'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'capacity'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.capacity = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'dataProfile'
val = data.get(property_name)
if val is not None:
datatypes = [EnumStoragePoolDataProfile]
try:
self.dataProfile = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'metadataProfile'
val = data.get(property_name)
if val is not None:
datatypes = [EnumStoragePoolMetadataProfile]
try:
self.metadataProfile = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'mountpoint'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.mountpoint = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'name'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.name = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [EnumStoragePoolStatus]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'totalCapacity'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.totalCapacity = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/StoragePool.py | StoragePool.py |
"""
Auto-generated class for JobListItem
"""
from . import client_support
class JobListItem(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(id, startTime):
"""
:type id: str
:type startTime: int
:rtype: JobListItem
"""
return JobListItem(
id=id,
startTime=startTime,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'JobListItem'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'id'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.id = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'startTime'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.startTime = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/JobListItem.py | JobListItem.py |
"""
Auto-generated class for VdiskListItem
"""
from .EnumVdiskListItemStatus import EnumVdiskListItemStatus
from .EnumVdiskListItemType import EnumVdiskListItemType
from . import client_support
class VdiskListItem(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(id, status, storagecluster, type):
"""
:type id: str
:type status: EnumVdiskListItemStatus
:type storagecluster: str
:type type: EnumVdiskListItemType
:rtype: VdiskListItem
"""
return VdiskListItem(
id=id,
status=status,
storagecluster=storagecluster,
type=type,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'VdiskListItem'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'id'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.id = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [EnumVdiskListItemStatus]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'storagecluster'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.storagecluster = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'type'
val = data.get(property_name)
if val is not None:
datatypes = [EnumVdiskListItemType]
try:
self.type = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/VdiskListItem.py | VdiskListItem.py |
"""
Auto-generated class for BridgeCreateSetting
"""
from . import client_support
class BridgeCreateSetting(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(cidr, end, start):
"""
:type cidr: str
:type end: str
:type start: str
:rtype: BridgeCreateSetting
"""
return BridgeCreateSetting(
cidr=cidr,
end=end,
start=start,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'BridgeCreateSetting'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'cidr'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.cidr = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'end'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.end = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'start'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.start = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/BridgeCreateSetting.py | BridgeCreateSetting.py |
from enum import Enum
class EnumContainerStatus(Enum):
running = "running"
halted = "halted"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/EnumContainerStatus.py | EnumContainerStatus.py |
"""
Auto-generated class for GWNICconfig
"""
from . import client_support
class GWNICconfig(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(cidr, gateway=None):
"""
:type cidr: str
:type gateway: str
:rtype: GWNICconfig
"""
return GWNICconfig(
cidr=cidr,
gateway=gateway,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'GWNICconfig'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'cidr'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.cidr = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'gateway'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.gateway = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/GWNICconfig.py | GWNICconfig.py |
"""
Auto-generated class for Dashboard
"""
from . import client_support
class Dashboard(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(dashboard, name):
"""
:type dashboard: str
:type name: str
:rtype: Dashboard
"""
return Dashboard(
dashboard=dashboard,
name=name,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'Dashboard'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'dashboard'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.dashboard = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'name'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.name = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/Dashboard.py | Dashboard.py |
"""
Auto-generated class for Container
"""
from .ContainerNIC import ContainerNIC
from .CoreSystem import CoreSystem
from .EnumContainerStatus import EnumContainerStatus
from . import client_support
class Container(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(filesystems, flist, hostNetworking, hostname, initprocesses, nics, ports, status, storage, zerotiernodeid=None):
"""
:type filesystems: list[str]
:type flist: str
:type hostNetworking: bool
:type hostname: str
:type initprocesses: list[CoreSystem]
:type nics: list[ContainerNIC]
:type ports: list[str]
:type status: EnumContainerStatus
:type storage: str
:type zerotiernodeid: str
:rtype: Container
"""
return Container(
filesystems=filesystems,
flist=flist,
hostNetworking=hostNetworking,
hostname=hostname,
initprocesses=initprocesses,
nics=nics,
ports=ports,
status=status,
storage=storage,
zerotiernodeid=zerotiernodeid,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'Container'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'filesystems'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.filesystems = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'flist'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.flist = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'hostNetworking'
val = data.get(property_name)
if val is not None:
datatypes = [bool]
try:
self.hostNetworking = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'hostname'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.hostname = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'initprocesses'
val = data.get(property_name)
if val is not None:
datatypes = [CoreSystem]
try:
self.initprocesses = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'nics'
val = data.get(property_name)
if val is not None:
datatypes = [ContainerNIC]
try:
self.nics = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'ports'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.ports = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [EnumContainerStatus]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'storage'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.storage = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'zerotiernodeid'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.zerotiernodeid = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/Container.py | Container.py |
"""
Auto-generated class for CloudInit
"""
from . import client_support
class CloudInit(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(metadata, userdata):
"""
:type metadata: str
:type userdata: str
:rtype: CloudInit
"""
return CloudInit(
metadata=metadata,
userdata=userdata,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'CloudInit'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'metadata'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.metadata = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'userdata'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.userdata = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/CloudInit.py | CloudInit.py |
"""
Auto-generated class for ZerotierJoin
"""
from . import client_support
class ZerotierJoin(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(nwid, token=None):
"""
:type nwid: str
:type token: str
:rtype: ZerotierJoin
"""
return ZerotierJoin(
nwid=nwid,
token=token,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'ZerotierJoin'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'nwid'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.nwid = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'token'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.token = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/ZerotierJoin.py | ZerotierJoin.py |
"""
Auto-generated class for NodeHealthCheck
"""
from . import client_support
class NodeHealthCheck(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(hostname, id, status):
"""
:type hostname: str
:type id: str
:type status: str
:rtype: NodeHealthCheck
"""
return NodeHealthCheck(
hostname=hostname,
id=id,
status=status,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'NodeHealthCheck'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'hostname'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.hostname = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'id'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.id = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/NodeHealthCheck.py | NodeHealthCheck.py |
"""
Auto-generated class for Bridge
"""
from .BridgeCreateSetting import BridgeCreateSetting
from .EnumBridgeStatus import EnumBridgeStatus
from . import client_support
class Bridge(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(name, setting, status):
"""
:type name: str
:type setting: BridgeCreateSetting
:type status: EnumBridgeStatus
:rtype: Bridge
"""
return Bridge(
name=name,
setting=setting,
status=status,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'Bridge'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'name'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.name = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'setting'
val = data.get(property_name)
if val is not None:
datatypes = [BridgeCreateSetting]
try:
self.setting = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [EnumBridgeStatus]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/Bridge.py | Bridge.py |
from enum import Enum
class HTTPType(Enum):
http = "http"
https = "https"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/HTTPType.py | HTTPType.py |
"""
Auto-generated class for VMNicInfo
"""
from . import client_support
class VMNicInfo(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(receivedPackets, receivedThroughput, transmittedPackets, transmittedThroughput):
"""
:type receivedPackets: int
:type receivedThroughput: int
:type transmittedPackets: int
:type transmittedThroughput: int
:rtype: VMNicInfo
"""
return VMNicInfo(
receivedPackets=receivedPackets,
receivedThroughput=receivedThroughput,
transmittedPackets=transmittedPackets,
transmittedThroughput=transmittedThroughput,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'VMNicInfo'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'receivedPackets'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.receivedPackets = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'receivedThroughput'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.receivedThroughput = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'transmittedPackets'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.transmittedPackets = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'transmittedThroughput'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.transmittedThroughput = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/VMNicInfo.py | VMNicInfo.py |
"""
Auto-generated class for DeleteFile
"""
from . import client_support
class DeleteFile(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(path):
"""
:type path: str
:rtype: DeleteFile
"""
return DeleteFile(
path=path,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'DeleteFile'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'path'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.path = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/DeleteFile.py | DeleteFile.py |
"""
Auto-generated class for NicLink
"""
from .EnumNicLinkType import EnumNicLinkType
from . import client_support
class NicLink(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(type, id=None, macaddress=None):
"""
:type id: str
:type macaddress: str
:type type: EnumNicLinkType
:rtype: NicLink
"""
return NicLink(
id=id,
macaddress=macaddress,
type=type,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'NicLink'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'id'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.id = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
property_name = 'macaddress'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.macaddress = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
property_name = 'type'
val = data.get(property_name)
if val is not None:
datatypes = [EnumNicLinkType]
try:
self.type = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/NicLink.py | NicLink.py |
"""
Auto-generated class for Filesystem
"""
from . import client_support
class Filesystem(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(mountpoint, name, parent, quota, readOnly, sizeOnDisk):
"""
:type mountpoint: str
:type name: str
:type parent: str
:type quota: int
:type readOnly: bool
:type sizeOnDisk: int
:rtype: Filesystem
"""
return Filesystem(
mountpoint=mountpoint,
name=name,
parent=parent,
quota=quota,
readOnly=readOnly,
sizeOnDisk=sizeOnDisk,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'Filesystem'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'mountpoint'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.mountpoint = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'name'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.name = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'parent'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.parent = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'quota'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.quota = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'readOnly'
val = data.get(property_name)
if val is not None:
datatypes = [bool]
try:
self.readOnly = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'sizeOnDisk'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.sizeOnDisk = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/Filesystem.py | Filesystem.py |
"""
Auto-generated class for ContainerNIC
"""
from .ContainerNICconfig import ContainerNICconfig
from .EnumContainerNICStatus import EnumContainerNICStatus
from .EnumContainerNICType import EnumContainerNICType
from . import client_support
class ContainerNIC(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(id, status, type, config=None, hwaddr=None, name=None, token=None):
"""
:type config: ContainerNICconfig
:type hwaddr: str
:type id: str
:type name: str
:type status: EnumContainerNICStatus
:type token: str
:type type: EnumContainerNICType
:rtype: ContainerNIC
"""
return ContainerNIC(
config=config,
hwaddr=hwaddr,
id=id,
name=name,
status=status,
token=token,
type=type,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'ContainerNIC'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'config'
val = data.get(property_name)
if val is not None:
datatypes = [ContainerNICconfig]
try:
self.config = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
property_name = 'hwaddr'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.hwaddr = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
property_name = 'id'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.id = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'name'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.name = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [EnumContainerNICStatus]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'token'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.token = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
property_name = 'type'
val = data.get(property_name)
if val is not None:
datatypes = [EnumContainerNICType]
try:
self.type = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/ContainerNIC.py | ContainerNIC.py |
"""
Auto-generated class for VdiskResize
"""
from . import client_support
class VdiskResize(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(newSize):
"""
:type newSize: int
:rtype: VdiskResize
"""
return VdiskResize(
newSize=newSize,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'VdiskResize'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'newSize'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.newSize = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/VdiskResize.py | VdiskResize.py |
"""
Auto-generated class for VMDiskInfo
"""
from . import client_support
class VMDiskInfo(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(readIops, readThroughput, writeIops, writeThroughput):
"""
:type readIops: int
:type readThroughput: int
:type writeIops: int
:type writeThroughput: int
:rtype: VMDiskInfo
"""
return VMDiskInfo(
readIops=readIops,
readThroughput=readThroughput,
writeIops=writeIops,
writeThroughput=writeThroughput,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'VMDiskInfo'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'readIops'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.readIops = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'readThroughput'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.readThroughput = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'writeIops'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.writeIops = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'writeThroughput'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.writeThroughput = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/VMDiskInfo.py | VMDiskInfo.py |
from enum import Enum
class EnumStoragePoolStatus(Enum):
healthy = "healthy"
degraded = "degraded"
error = "error"
unknown = "unknown"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/EnumStoragePoolStatus.py | EnumStoragePoolStatus.py |
"""
Auto-generated class for JobResult
"""
from .EnumJobResultName import EnumJobResultName
from .EnumJobResultState import EnumJobResultState
from . import client_support
class JobResult(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(data, id, level, name, startTime, state, stderr, stdout):
"""
:type data: str
:type id: str
:type level: int
:type name: EnumJobResultName
:type startTime: int
:type state: EnumJobResultState
:type stderr: str
:type stdout: str
:rtype: JobResult
"""
return JobResult(
data=data,
id=id,
level=level,
name=name,
startTime=startTime,
state=state,
stderr=stderr,
stdout=stdout,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'JobResult'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'data'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.data = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'id'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.id = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'level'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.level = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'name'
val = data.get(property_name)
if val is not None:
datatypes = [EnumJobResultName]
try:
self.name = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'startTime'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.startTime = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'state'
val = data.get(property_name)
if val is not None:
datatypes = [EnumJobResultState]
try:
self.state = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'stderr'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.stderr = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'stdout'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.stdout = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/JobResult.py | JobResult.py |
"""
support methods for python clients
"""
import json
import collections
from datetime import datetime
from uuid import UUID
from enum import Enum
from dateutil import parser
# python2/3 compatible basestring, for use in to_dict
try:
basestring
except NameError:
basestring = str
def timestamp_from_datetime(datetime):
"""
Convert from datetime format to timestamp format
Input: Time in datetime format
Output: Time in timestamp format
"""
return datetime.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
def timestamp_to_datetime(timestamp):
"""
Convert from timestamp format to datetime format
Input: Time in timestamp format
Output: Time in datetime format
"""
return parser.parse(timestamp).replace(tzinfo=None)
def has_properties(cls, property, child_properties):
for child_prop in child_properties:
if getattr(property, child_prop, None) is None:
return False
return True
def list_factory(val, member_type):
if not isinstance(val, list):
raise ValueError('list_factory: value must be a list')
return [val_factory(v, member_type) for v in val]
def dict_factory(val, objmap):
# objmap is a dict outlining the structure of this value
# its format is {'attrname': {'datatype': [type], 'required': bool}}
objdict = {}
for attrname, attrdict in objmap.items():
value = val.get(attrname)
if value is not None:
for dt in attrdict['datatype']:
try:
if isinstance(dt, dict):
objdict[attrname] = dict_factory(value, attrdict)
else:
objdict[attrname] = val_factory(value, [dt])
except Exception:
pass
if objdict.get(attrname) is None:
raise ValueError('dict_factory: {attr}: unable to instantiate with any supplied type'.format(attr=attrname))
elif attrdict.get('required'):
raise ValueError('dict_factory: {attr} is required'.format(attr=attrname))
return objdict
def val_factory(val, datatypes):
"""
return an instance of `val` that is of type `datatype`.
keep track of exceptions so we can produce meaningful error messages.
"""
exceptions = []
for dt in datatypes:
try:
if isinstance(val, dt):
return val
return type_handler_object(val, dt)
except Exception as e:
exceptions.append(str(e))
# if we get here, we never found a valid value. raise an error
raise ValueError('val_factory: Unable to instantiate {val} from types {types}. Exceptions: {excs}'.
format(val=val, types=datatypes, excs=exceptions))
def to_json(cls, indent=0):
"""
serialize to JSON
:rtype: str
"""
# for consistency, use as_dict then go to json from there
return json.dumps(cls.as_dict(), indent=indent)
def to_dict(cls, convert_datetime=True):
"""
return a dict representation of the Event and its sub-objects
`convert_datetime` controls whether datetime objects are converted to strings or not
:rtype: dict
"""
def todict(obj):
"""
recurse the objects and represent as a dict
use the registered handlers if possible
"""
data = {}
if isinstance(obj, dict):
for (key, val) in obj.items():
data[key] = todict(val)
return data
if not convert_datetime and isinstance(obj, datetime):
return obj
elif type_handler_value(obj):
return type_handler_value(obj)
elif isinstance(obj, collections.Sequence) and not isinstance(obj, basestring):
return [todict(v) for v in obj]
elif hasattr(obj, "__dict__"):
for key, value in obj.__dict__.items():
if not callable(value) and not key.startswith('_'):
data[key] = todict(value)
return data
else:
return obj
return todict(cls)
class DatetimeHandler(object):
"""
output datetime objects as iso-8601 compliant strings
"""
@classmethod
def flatten(cls, obj):
"""flatten"""
return timestamp_from_datetime(obj)
@classmethod
def restore(cls, data):
"""restore"""
return timestamp_to_datetime(data)
class UUIDHandler(object):
"""
output UUID objects as a string
"""
@classmethod
def flatten(cls, obj):
"""flatten"""
return str(obj)
@classmethod
def restore(cls, data):
"""restore"""
return UUID(data)
class EnumHandler(object):
"""
output Enum objects as their value
"""
@classmethod
def flatten(cls, obj):
"""flatten"""
return obj.value
@classmethod
def restore(cls, data):
"""
cannot restore here because we don't know what type of enum it is
"""
raise NotImplementedError
handlers = {
datetime: DatetimeHandler,
Enum: EnumHandler,
UUID: UUIDHandler,
}
def handler_for(obj):
"""return the handler for the object type"""
for handler_type in handlers:
if isinstance(obj, handler_type):
return handlers[handler_type]
try:
for handler_type in handlers:
if issubclass(obj, handler_type):
return handlers[handler_type]
except TypeError:
# if obj isn't a class, issubclass will raise a TypeError
pass
def type_handler_value(obj):
"""
return the serialized (flattened) value from the registered handler for the type
"""
handler = handler_for(obj)
if handler:
return handler().flatten(obj)
def type_handler_object(val, objtype):
"""
return the deserialized (restored) value from the registered handler for the type
"""
handler = handlers.get(objtype)
if handler:
return handler().restore(val)
else:
return objtype(val) | 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/client_support.py | client_support.py |
"""
Auto-generated class for DiskInfo
"""
from .DiskPartition import DiskPartition
from .EnumDiskInfoType import EnumDiskInfoType
from . import client_support
class DiskInfo(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(device, partitions, size, type):
"""
:type device: str
:type partitions: list[DiskPartition]
:type size: int
:type type: EnumDiskInfoType
:rtype: DiskInfo
"""
return DiskInfo(
device=device,
partitions=partitions,
size=size,
type=type,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'DiskInfo'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'device'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.device = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'partitions'
val = data.get(property_name)
if val is not None:
datatypes = [DiskPartition]
try:
self.partitions = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'size'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.size = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'type'
val = data.get(property_name)
if val is not None:
datatypes = [EnumDiskInfoType]
try:
self.type = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/DiskInfo.py | DiskInfo.py |
from enum import Enum
class EnumNicLinkType(Enum):
vlan = "vlan"
vxlan = "vxlan"
default = "default"
bridge = "bridge"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/EnumNicLinkType.py | EnumNicLinkType.py |
"""
Auto-generated class for PortForward
"""
from .IPProtocol import IPProtocol
from . import client_support
class PortForward(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(dstip, dstport, protocols, srcip, srcport):
"""
:type dstip: str
:type dstport: int
:type protocols: list[IPProtocol]
:type srcip: str
:type srcport: int
:rtype: PortForward
"""
return PortForward(
dstip=dstip,
dstport=dstport,
protocols=protocols,
srcip=srcip,
srcport=srcport,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'PortForward'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'dstip'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.dstip = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'dstport'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.dstport = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'protocols'
val = data.get(property_name)
if val is not None:
datatypes = [IPProtocol]
try:
self.protocols = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'srcip'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.srcip = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'srcport'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.srcport = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/PortForward.py | PortForward.py |
"""
Auto-generated class for ContainerListItem
"""
from .EnumContainerListItemStatus import EnumContainerListItemStatus
from . import client_support
class ContainerListItem(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(flist, hostname, name, status):
"""
:type flist: str
:type hostname: str
:type name: str
:type status: EnumContainerListItemStatus
:rtype: ContainerListItem
"""
return ContainerListItem(
flist=flist,
hostname=hostname,
name=name,
status=status,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'ContainerListItem'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'flist'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.flist = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'hostname'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.hostname = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'name'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.name = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [EnumContainerListItemStatus]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/ContainerListItem.py | ContainerListItem.py |
"""
Auto-generated class for ContainerNICconfig
"""
from . import client_support
class ContainerNICconfig(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(cidr, dhcp, dns=None, gateway=None):
"""
:type cidr: str
:type dhcp: bool
:type dns: list[str]
:type gateway: str
:rtype: ContainerNICconfig
"""
return ContainerNICconfig(
cidr=cidr,
dhcp=dhcp,
dns=dns,
gateway=gateway,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'ContainerNICconfig'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'cidr'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.cidr = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'dhcp'
val = data.get(property_name)
if val is not None:
datatypes = [bool]
try:
self.dhcp = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'dns'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.dns = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
property_name = 'gateway'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.gateway = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/ContainerNICconfig.py | ContainerNICconfig.py |
"""
Auto-generated class for Job
"""
from . import client_support
class Job(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(id, logLevels, maxRestart, maxTime, queue, recurringPeriod, statsInterval, tags):
"""
:type id: str
:type logLevels: list[int]
:type maxRestart: int
:type maxTime: int
:type queue: str
:type recurringPeriod: int
:type statsInterval: int
:type tags: str
:rtype: Job
"""
return Job(
id=id,
logLevels=logLevels,
maxRestart=maxRestart,
maxTime=maxTime,
queue=queue,
recurringPeriod=recurringPeriod,
statsInterval=statsInterval,
tags=tags,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'Job'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'id'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.id = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'logLevels'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.logLevels = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'maxRestart'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.maxRestart = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'maxTime'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.maxTime = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'queue'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.queue = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'recurringPeriod'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.recurringPeriod = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'statsInterval'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.statsInterval = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'tags'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.tags = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/Job.py | Job.py |
from enum import Enum
class EnumNodeStatus(Enum):
running = "running"
halted = "halted"
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/EnumNodeStatus.py | EnumNodeStatus.py |
"""
Auto-generated class for Vdisk
"""
from .EnumVdiskStatus import EnumVdiskStatus
from .EnumVdiskType import EnumVdiskType
from . import client_support
class Vdisk(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(blocksize, id, size, status, storagecluster, tlogStoragecluster, type, readOnly=None):
"""
:type blocksize: int
:type id: str
:type readOnly: bool
:type size: int
:type status: EnumVdiskStatus
:type storagecluster: str
:type tlogStoragecluster: str
:type type: EnumVdiskType
:rtype: Vdisk
"""
return Vdisk(
blocksize=blocksize,
id=id,
readOnly=readOnly,
size=size,
status=status,
storagecluster=storagecluster,
tlogStoragecluster=tlogStoragecluster,
type=type,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'Vdisk'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'blocksize'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.blocksize = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'id'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.id = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'readOnly'
val = data.get(property_name)
if val is not None:
datatypes = [bool]
try:
self.readOnly = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
property_name = 'size'
val = data.get(property_name)
if val is not None:
datatypes = [int]
try:
self.size = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [EnumVdiskStatus]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'storagecluster'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.storagecluster = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'tlogStoragecluster'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.tlogStoragecluster = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'type'
val = data.get(property_name)
if val is not None:
datatypes = [EnumVdiskType]
try:
self.type = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/Vdisk.py | Vdisk.py |
"""
Auto-generated class for GetGW
"""
from .EnumGetGWStatus import EnumGetGWStatus
from .GWNIC import GWNIC
from .HTTPProxy import HTTPProxy
from .PortForward import PortForward
from . import client_support
class GetGW(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(domain, nics, status, httpproxies=None, portforwards=None, zerotiernodeid=None):
"""
:type domain: str
:type httpproxies: list[HTTPProxy]
:type nics: list[GWNIC]
:type portforwards: list[PortForward]
:type status: EnumGetGWStatus
:type zerotiernodeid: str
:rtype: GetGW
"""
return GetGW(
domain=domain,
httpproxies=httpproxies,
nics=nics,
portforwards=portforwards,
status=status,
zerotiernodeid=zerotiernodeid,
)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'GetGW'
create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
required_error = '{cls}: missing required property {prop}'
data = json or kwargs
property_name = 'domain'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.domain = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'httpproxies'
val = data.get(property_name)
if val is not None:
datatypes = [HTTPProxy]
try:
self.httpproxies = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
property_name = 'nics'
val = data.get(property_name)
if val is not None:
datatypes = [GWNIC]
try:
self.nics = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'portforwards'
val = data.get(property_name)
if val is not None:
datatypes = [PortForward]
try:
self.portforwards = client_support.list_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
property_name = 'status'
val = data.get(property_name)
if val is not None:
datatypes = [EnumGetGWStatus]
try:
self.status = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
else:
raise ValueError(required_error.format(cls=class_name, prop=property_name))
property_name = 'zerotiernodeid'
val = data.get(property_name)
if val is not None:
datatypes = [str]
try:
self.zerotiernodeid = client_support.val_factory(val, datatypes)
except ValueError as err:
raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| 0-orchestrator | /0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/GetGW.py | GetGW.py |
End of preview. Expand
in Dataset Viewer.
Dataset Card for "pypi_raw"
All of the latest package versions from pypi. The original data came from here. I pulled the latest versions of each package, then extracted only md
, rst
, ipynb
, and py
files. See other datasets for versions that have been cleaned and labeled.
- Downloads last month
- 56