repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
thecynic/pylutron | pylutron/__init__.py | Keypad.add_led | def add_led(self, led):
"""Add an LED that's part of this keypad."""
self._leds.append(led)
self._components[led.component_number] = led | python | def add_led(self, led):
"""Add an LED that's part of this keypad."""
self._leds.append(led)
self._components[led.component_number] = led | Add an LED that's part of this keypad. | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L808-L811 |
thecynic/pylutron | pylutron/__init__.py | Keypad.handle_update | def handle_update(self, args):
"""The callback invoked by the main event loop if there's an event from this keypad."""
component = int(args[0])
action = int(args[1])
params = [int(x) for x in args[2:]]
_LOGGER.debug("Updating %d(%s): c=%d a=%d params=%s" % (
self._integration_id, self._name, component, action, params))
if component in self._components:
return self._components[component].handle_update(action, params)
return False | python | def handle_update(self, args):
"""The callback invoked by the main event loop if there's an event from this keypad."""
component = int(args[0])
action = int(args[1])
params = [int(x) for x in args[2:]]
_LOGGER.debug("Updating %d(%s): c=%d a=%d params=%s" % (
self._integration_id, self._name, component, action, params))
if component in self._components:
return self._components[component].handle_update(action, params)
return False | The callback invoked by the main event loop if there's an event from this keypad. | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L833-L842 |
oasis-open/cti-pattern-validator | stix2patterns/validator.py | run_validator | def run_validator(pattern):
"""
Validates a pattern against the STIX Pattern grammar. Error messages are
returned in a list. The test passed if the returned list is empty.
"""
start = ''
if isinstance(pattern, six.string_types):
start = pattern[:2]
pattern = InputStream(pattern)
if not start:
start = pattern.readline()[:2]
pattern.seek(0)
parseErrListener = STIXPatternErrorListener()
lexer = STIXPatternLexer(pattern)
# it always adds a console listener by default... remove it.
lexer.removeErrorListeners()
stream = CommonTokenStream(lexer)
parser = STIXPatternParser(stream)
parser.buildParseTrees = False
# it always adds a console listener by default... remove it.
parser.removeErrorListeners()
parser.addErrorListener(parseErrListener)
# To improve error messages, replace "<INVALID>" in the literal
# names with symbolic names. This is a hack, but seemed like
# the simplest workaround.
for i, lit_name in enumerate(parser.literalNames):
if lit_name == u"<INVALID>":
parser.literalNames[i] = parser.symbolicNames[i]
parser.pattern()
# replace with easier-to-understand error message
if not (start[0] == '[' or start == '(['):
parseErrListener.err_strings[0] = "FAIL: Error found at line 1:0. " \
"input is missing square brackets"
return parseErrListener.err_strings | python | def run_validator(pattern):
"""
Validates a pattern against the STIX Pattern grammar. Error messages are
returned in a list. The test passed if the returned list is empty.
"""
start = ''
if isinstance(pattern, six.string_types):
start = pattern[:2]
pattern = InputStream(pattern)
if not start:
start = pattern.readline()[:2]
pattern.seek(0)
parseErrListener = STIXPatternErrorListener()
lexer = STIXPatternLexer(pattern)
# it always adds a console listener by default... remove it.
lexer.removeErrorListeners()
stream = CommonTokenStream(lexer)
parser = STIXPatternParser(stream)
parser.buildParseTrees = False
# it always adds a console listener by default... remove it.
parser.removeErrorListeners()
parser.addErrorListener(parseErrListener)
# To improve error messages, replace "<INVALID>" in the literal
# names with symbolic names. This is a hack, but seemed like
# the simplest workaround.
for i, lit_name in enumerate(parser.literalNames):
if lit_name == u"<INVALID>":
parser.literalNames[i] = parser.symbolicNames[i]
parser.pattern()
# replace with easier-to-understand error message
if not (start[0] == '[' or start == '(['):
parseErrListener.err_strings[0] = "FAIL: Error found at line 1:0. " \
"input is missing square brackets"
return parseErrListener.err_strings | Validates a pattern against the STIX Pattern grammar. Error messages are
returned in a list. The test passed if the returned list is empty. | https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/validator.py#L31-L74 |
oasis-open/cti-pattern-validator | stix2patterns/validator.py | validate | def validate(user_input, ret_errs=False, print_errs=False):
"""
Wrapper for run_validator function that returns True if the user_input
contains a valid STIX pattern or False otherwise. The error messages may
also be returned or printed based upon the ret_errs and print_errs arg
values.
"""
errs = run_validator(user_input)
passed = len(errs) == 0
if print_errs:
for err in errs:
print(err)
if ret_errs:
return passed, errs
return passed | python | def validate(user_input, ret_errs=False, print_errs=False):
"""
Wrapper for run_validator function that returns True if the user_input
contains a valid STIX pattern or False otherwise. The error messages may
also be returned or printed based upon the ret_errs and print_errs arg
values.
"""
errs = run_validator(user_input)
passed = len(errs) == 0
if print_errs:
for err in errs:
print(err)
if ret_errs:
return passed, errs
return passed | Wrapper for run_validator function that returns True if the user_input
contains a valid STIX pattern or False otherwise. The error messages may
also be returned or printed based upon the ret_errs and print_errs arg
values. | https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/validator.py#L77-L95 |
oasis-open/cti-pattern-validator | stix2patterns/validator.py | main | def main():
"""
Continues to validate patterns until it encounters EOF within a pattern
file or Ctrl-C is pressed by the user.
"""
parser = argparse.ArgumentParser(description='Validate STIX Patterns.')
parser.add_argument('-f', '--file',
help="Specify this arg to read patterns from a file.",
type=argparse.FileType("r"))
args = parser.parse_args()
pass_count = fail_count = 0
# I tried using a generator (where each iteration would run raw_input()),
# but raw_input()'s behavior seems to change when called from within a
# generator: I only get one line, then the generator completes! I don't
# know why behavior changes...
import functools
if args.file:
nextpattern = args.file.readline
else:
nextpattern = functools.partial(six.moves.input, "Enter a pattern to validate: ")
try:
while True:
pattern = nextpattern()
if not pattern:
break
tests_passed, err_strings = validate(pattern, True)
if tests_passed:
print("\nPASS: %s" % pattern)
pass_count += 1
else:
for err in err_strings:
print(err, '\n')
fail_count += 1
except (EOFError, KeyboardInterrupt):
pass
finally:
if args.file:
args.file.close()
print("\nPASSED:", pass_count, " patterns")
print("FAILED:", fail_count, " patterns") | python | def main():
"""
Continues to validate patterns until it encounters EOF within a pattern
file or Ctrl-C is pressed by the user.
"""
parser = argparse.ArgumentParser(description='Validate STIX Patterns.')
parser.add_argument('-f', '--file',
help="Specify this arg to read patterns from a file.",
type=argparse.FileType("r"))
args = parser.parse_args()
pass_count = fail_count = 0
# I tried using a generator (where each iteration would run raw_input()),
# but raw_input()'s behavior seems to change when called from within a
# generator: I only get one line, then the generator completes! I don't
# know why behavior changes...
import functools
if args.file:
nextpattern = args.file.readline
else:
nextpattern = functools.partial(six.moves.input, "Enter a pattern to validate: ")
try:
while True:
pattern = nextpattern()
if not pattern:
break
tests_passed, err_strings = validate(pattern, True)
if tests_passed:
print("\nPASS: %s" % pattern)
pass_count += 1
else:
for err in err_strings:
print(err, '\n')
fail_count += 1
except (EOFError, KeyboardInterrupt):
pass
finally:
if args.file:
args.file.close()
print("\nPASSED:", pass_count, " patterns")
print("FAILED:", fail_count, " patterns") | Continues to validate patterns until it encounters EOF within a pattern
file or Ctrl-C is pressed by the user. | https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/validator.py#L98-L143 |
oasis-open/cti-pattern-validator | stix2patterns/inspector.py | _string_literal_to_string | def _string_literal_to_string(string_literal_token):
"""Converts the StringLiteral token to a plain string: get text content,
removes quote characters, and unescapes it.
:param string_literal_token: The string literal
:return:
"""
token_text = string_literal_token.getText()
return token_text[1:-1].replace(u"\\'", u"'"). \
replace(u"\\\\", u"\\") | python | def _string_literal_to_string(string_literal_token):
"""Converts the StringLiteral token to a plain string: get text content,
removes quote characters, and unescapes it.
:param string_literal_token: The string literal
:return:
"""
token_text = string_literal_token.getText()
return token_text[1:-1].replace(u"\\'", u"'"). \
replace(u"\\\\", u"\\") | Converts the StringLiteral token to a plain string: get text content,
removes quote characters, and unescapes it.
:param string_literal_token: The string literal
:return: | https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/inspector.py#L19-L28 |
alexhayes/django-pdfkit | django_pdfkit/views.py | PDFView.get | def get(self, request, *args, **kwargs):
"""
Return a HTTPResponse either of a PDF file or HTML.
:rtype: HttpResponse
"""
if 'html' in request.GET:
# Output HTML
content = self.render_html(*args, **kwargs)
return HttpResponse(content)
else:
# Output PDF
content = self.render_pdf(*args, **kwargs)
response = HttpResponse(content, content_type='application/pdf')
if (not self.inline or 'download' in request.GET) and 'inline' not in request.GET:
response['Content-Disposition'] = 'attachment; filename=%s' % self.get_filename()
response['Content-Length'] = len(content)
return response | python | def get(self, request, *args, **kwargs):
"""
Return a HTTPResponse either of a PDF file or HTML.
:rtype: HttpResponse
"""
if 'html' in request.GET:
# Output HTML
content = self.render_html(*args, **kwargs)
return HttpResponse(content)
else:
# Output PDF
content = self.render_pdf(*args, **kwargs)
response = HttpResponse(content, content_type='application/pdf')
if (not self.inline or 'download' in request.GET) and 'inline' not in request.GET:
response['Content-Disposition'] = 'attachment; filename=%s' % self.get_filename()
response['Content-Length'] = len(content)
return response | Return a HTTPResponse either of a PDF file or HTML.
:rtype: HttpResponse | https://github.com/alexhayes/django-pdfkit/blob/02774ae2cb67d05dd5e4cb50661c56464ebb2413/django_pdfkit/views.py#L31-L53 |
alexhayes/django-pdfkit | django_pdfkit/views.py | PDFView.render_pdf | def render_pdf(self, *args, **kwargs):
"""
Render the PDF and returns as bytes.
:rtype: bytes
"""
html = self.render_html(*args, **kwargs)
options = self.get_pdfkit_options()
if 'debug' in self.request.GET and settings.DEBUG:
options['debug-javascript'] = 1
kwargs = {}
wkhtmltopdf_bin = os.environ.get('WKHTMLTOPDF_BIN')
if wkhtmltopdf_bin:
kwargs['configuration'] = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_bin)
pdf = pdfkit.from_string(html, False, options, **kwargs)
return pdf | python | def render_pdf(self, *args, **kwargs):
"""
Render the PDF and returns as bytes.
:rtype: bytes
"""
html = self.render_html(*args, **kwargs)
options = self.get_pdfkit_options()
if 'debug' in self.request.GET and settings.DEBUG:
options['debug-javascript'] = 1
kwargs = {}
wkhtmltopdf_bin = os.environ.get('WKHTMLTOPDF_BIN')
if wkhtmltopdf_bin:
kwargs['configuration'] = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_bin)
pdf = pdfkit.from_string(html, False, options, **kwargs)
return pdf | Render the PDF and returns as bytes.
:rtype: bytes | https://github.com/alexhayes/django-pdfkit/blob/02774ae2cb67d05dd5e4cb50661c56464ebb2413/django_pdfkit/views.py#L55-L74 |
alexhayes/django-pdfkit | django_pdfkit/views.py | PDFView.get_filename | def get_filename(self):
"""
Return ``self.filename`` if set otherwise return the template basename with a ``.pdf`` extension.
:rtype: str
"""
if self.filename is None:
name = splitext(basename(self.template_name))[0]
return '{}.pdf'.format(name)
return self.filename | python | def get_filename(self):
"""
Return ``self.filename`` if set otherwise return the template basename with a ``.pdf`` extension.
:rtype: str
"""
if self.filename is None:
name = splitext(basename(self.template_name))[0]
return '{}.pdf'.format(name)
return self.filename | Return ``self.filename`` if set otherwise return the template basename with a ``.pdf`` extension.
:rtype: str | https://github.com/alexhayes/django-pdfkit/blob/02774ae2cb67d05dd5e4cb50661c56464ebb2413/django_pdfkit/views.py#L90-L100 |
alexhayes/django-pdfkit | django_pdfkit/views.py | PDFView.render_html | def render_html(self, *args, **kwargs):
"""
Renders the template.
:rtype: str
"""
static_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.STATIC_URL)
media_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.MEDIA_URL)
with override_settings(STATIC_URL=static_url, MEDIA_URL=media_url):
template = loader.get_template(self.template_name)
context = self.get_context_data(*args, **kwargs)
html = template.render(context)
return html | python | def render_html(self, *args, **kwargs):
"""
Renders the template.
:rtype: str
"""
static_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.STATIC_URL)
media_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.MEDIA_URL)
with override_settings(STATIC_URL=static_url, MEDIA_URL=media_url):
template = loader.get_template(self.template_name)
context = self.get_context_data(*args, **kwargs)
html = template.render(context)
return html | Renders the template.
:rtype: str | https://github.com/alexhayes/django-pdfkit/blob/02774ae2cb67d05dd5e4cb50661c56464ebb2413/django_pdfkit/views.py#L102-L115 |
oasis-open/cti-pattern-validator | stix2patterns/pattern.py | Pattern.inspect | def inspect(self):
"""
Inspect a pattern. This gives information regarding the sorts of
operations, content, etc in use in the pattern.
:return: Pattern information
"""
inspector = stix2patterns.inspector.InspectionListener()
self.walk(inspector)
return inspector.pattern_data() | python | def inspect(self):
"""
Inspect a pattern. This gives information regarding the sorts of
operations, content, etc in use in the pattern.
:return: Pattern information
"""
inspector = stix2patterns.inspector.InspectionListener()
self.walk(inspector)
return inspector.pattern_data() | Inspect a pattern. This gives information regarding the sorts of
operations, content, etc in use in the pattern.
:return: Pattern information | https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/pattern.py#L36-L47 |
oasis-open/cti-pattern-validator | stix2patterns/pattern.py | Pattern.walk | def walk(self, listener):
"""Walk the parse tree, using the given listener. The listener
should be a
stix2patterns.grammars.STIXPatternListener.STIXPatternListener (or
subclass) instance."""
antlr4.ParseTreeWalker.DEFAULT.walk(listener, self.__parse_tree) | python | def walk(self, listener):
"""Walk the parse tree, using the given listener. The listener
should be a
stix2patterns.grammars.STIXPatternListener.STIXPatternListener (or
subclass) instance."""
antlr4.ParseTreeWalker.DEFAULT.walk(listener, self.__parse_tree) | Walk the parse tree, using the given listener. The listener
should be a
stix2patterns.grammars.STIXPatternListener.STIXPatternListener (or
subclass) instance. | https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/pattern.py#L49-L54 |
oasis-open/cti-pattern-validator | stix2patterns/pattern.py | Pattern.__do_parse | def __do_parse(self, pattern_str):
"""
Parses the given pattern and returns the antlr parse tree.
:param pattern_str: The STIX pattern
:return: The parse tree
:raises ParseException: If there is a parse error
"""
in_ = antlr4.InputStream(pattern_str)
lexer = STIXPatternLexer(in_)
lexer.removeErrorListeners() # remove the default "console" listener
token_stream = antlr4.CommonTokenStream(lexer)
parser = STIXPatternParser(token_stream)
parser.removeErrorListeners() # remove the default "console" listener
error_listener = ParserErrorListener()
parser.addErrorListener(error_listener)
# I found no public API for this...
# The default error handler tries to keep parsing, and I don't
# think that's appropriate here. (These error handlers are only for
# handling the built-in RecognitionException errors.)
parser._errHandler = antlr4.BailErrorStrategy()
# To improve error messages, replace "<INVALID>" in the literal
# names with symbolic names. This is a hack, but seemed like
# the simplest workaround.
for i, lit_name in enumerate(parser.literalNames):
if lit_name == u"<INVALID>":
parser.literalNames[i] = parser.symbolicNames[i]
# parser.setTrace(True)
try:
tree = parser.pattern()
# print(tree.toStringTree(recog=parser))
return tree
except antlr4.error.Errors.ParseCancellationException as e:
# The cancellation exception wraps the real RecognitionException
# which caused the parser to bail.
real_exc = e.args[0]
# I want to bail when the first error is hit. But I also want
# a decent error message. When an error is encountered in
# Parser.match(), the BailErrorStrategy produces the
# ParseCancellationException. It is not a subclass of
# RecognitionException, so none of the 'except' clauses which would
# normally report an error are invoked.
#
# Error message creation is buried in the ErrorStrategy, and I can
# (ab)use the API to get a message: register an error listener with
# the parser, force an error report, then get the message out of the
# listener. Error listener registration is above; now we force its
# invocation. Wish this could be cleaner...
parser._errHandler.reportError(parser, real_exc)
# should probably chain exceptions if we can...
# Should I report the cancellation or recognition exception as the
# cause...?
six.raise_from(ParseException(error_listener.error_message),
real_exc) | python | def __do_parse(self, pattern_str):
"""
Parses the given pattern and returns the antlr parse tree.
:param pattern_str: The STIX pattern
:return: The parse tree
:raises ParseException: If there is a parse error
"""
in_ = antlr4.InputStream(pattern_str)
lexer = STIXPatternLexer(in_)
lexer.removeErrorListeners() # remove the default "console" listener
token_stream = antlr4.CommonTokenStream(lexer)
parser = STIXPatternParser(token_stream)
parser.removeErrorListeners() # remove the default "console" listener
error_listener = ParserErrorListener()
parser.addErrorListener(error_listener)
# I found no public API for this...
# The default error handler tries to keep parsing, and I don't
# think that's appropriate here. (These error handlers are only for
# handling the built-in RecognitionException errors.)
parser._errHandler = antlr4.BailErrorStrategy()
# To improve error messages, replace "<INVALID>" in the literal
# names with symbolic names. This is a hack, but seemed like
# the simplest workaround.
for i, lit_name in enumerate(parser.literalNames):
if lit_name == u"<INVALID>":
parser.literalNames[i] = parser.symbolicNames[i]
# parser.setTrace(True)
try:
tree = parser.pattern()
# print(tree.toStringTree(recog=parser))
return tree
except antlr4.error.Errors.ParseCancellationException as e:
# The cancellation exception wraps the real RecognitionException
# which caused the parser to bail.
real_exc = e.args[0]
# I want to bail when the first error is hit. But I also want
# a decent error message. When an error is encountered in
# Parser.match(), the BailErrorStrategy produces the
# ParseCancellationException. It is not a subclass of
# RecognitionException, so none of the 'except' clauses which would
# normally report an error are invoked.
#
# Error message creation is buried in the ErrorStrategy, and I can
# (ab)use the API to get a message: register an error listener with
# the parser, force an error report, then get the message out of the
# listener. Error listener registration is above; now we force its
# invocation. Wish this could be cleaner...
parser._errHandler.reportError(parser, real_exc)
# should probably chain exceptions if we can...
# Should I report the cancellation or recognition exception as the
# cause...?
six.raise_from(ParseException(error_listener.error_message),
real_exc) | Parses the given pattern and returns the antlr parse tree.
:param pattern_str: The STIX pattern
:return: The parse tree
:raises ParseException: If there is a parse error | https://github.com/oasis-open/cti-pattern-validator/blob/753a6901120db25f0c8550607de1eab4440d59df/stix2patterns/pattern.py#L56-L117 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | Return.stdout | def stdout(self):
"""
The job stdout
:return: string or None
"""
streams = self._payload.get('streams', None)
return streams[0] if streams is not None and len(streams) >= 1 else '' | python | def stdout(self):
"""
The job stdout
:return: string or None
"""
streams = self._payload.get('streams', None)
return streams[0] if streams is not None and len(streams) >= 1 else '' | The job stdout
:return: string or None | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L102-L108 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | Return.stderr | def stderr(self):
"""
The job stderr
:return: string or None
"""
streams = self._payload.get('streams', None)
return streams[1] if streams is not None and len(streams) >= 2 else '' | python | def stderr(self):
"""
The job stderr
:return: string or None
"""
streams = self._payload.get('streams', None)
return streams[1] if streams is not None and len(streams) >= 2 else '' | The job stderr
:return: string or None | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L111-L117 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | Response.exists | def exists(self):
"""
Returns true if the job is still running or zero-os still knows about this job ID
After a job is finished, a job remains on zero-os for max of 5min where you still can read the job result
after the 5 min is gone, the job result is no more fetchable
:return: bool
"""
r = self._client._redis
flag = '{}:flag'.format(self._queue)
return bool(r.exists(flag)) | python | def exists(self):
"""
Returns true if the job is still running or zero-os still knows about this job ID
After a job is finished, a job remains on zero-os for max of 5min where you still can read the job result
after the 5 min is gone, the job result is no more fetchable
:return: bool
"""
r = self._client._redis
flag = '{}:flag'.format(self._queue)
return bool(r.exists(flag)) | Returns true if the job is still running or zero-os still knows about this job ID
After a job is finished, a job remains on zero-os for max of 5min where you still can read the job result
after the 5 min is gone, the job result is no more fetchable
:return: bool | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L162-L172 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | Response.running | def running(self):
"""
Returns true if job still in running state
:return:
"""
r = self._client._redis
flag = '{}:flag'.format(self._queue)
if bool(r.exists(flag)):
return r.ttl(flag) is None
return False | python | def running(self):
"""
Returns true if job still in running state
:return:
"""
r = self._client._redis
flag = '{}:flag'.format(self._queue)
if bool(r.exists(flag)):
return r.ttl(flag) is None
return False | Returns true if job still in running state
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L175-L185 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | Response.stream | def stream(self, callback=None):
"""
Runtime copy of job messages. This required the 'stream` flag to be set to True otherwise it will
not be able to copy any output, while it will block until the process exits.
:note: This function will block until it reaches end of stream or the process is no longer running.
:param callback: callback method that will get called for each received message
callback accepts 3 arguments
- level int: the log message levels, refer to the docs for available levels
and their meanings
- message str: the actual output message
- flags int: flags associated with this message
- 0x2 means EOF with success exit status
- 0x4 means EOF with error
for example (eof = flag & 0x6) eof will be true for last message u will ever
receive on this callback.
Note: if callback is none, a default callback will be used that prints output on stdout/stderr
based on level.
:return: None
"""
if callback is None:
callback = Response.__default
if not callable(callback):
raise Exception('callback must be callable')
queue = 'stream:%s' % self.id
r = self._client._redis
# we can terminate quickly by checking if the process is not running and it has no queued output.
# if not self.running and r.llen(queue) == 0:
# return
while True:
data = r.blpop(queue, 10)
if data is None:
if not self.running:
break
continue
_, body = data
payload = json.loads(body.decode())
message = payload['message']
line = message['message']
meta = message['meta']
callback(meta >> 16, line, meta & 0xff)
if meta & 0x6 != 0:
break | python | def stream(self, callback=None):
"""
Runtime copy of job messages. This required the 'stream` flag to be set to True otherwise it will
not be able to copy any output, while it will block until the process exits.
:note: This function will block until it reaches end of stream or the process is no longer running.
:param callback: callback method that will get called for each received message
callback accepts 3 arguments
- level int: the log message levels, refer to the docs for available levels
and their meanings
- message str: the actual output message
- flags int: flags associated with this message
- 0x2 means EOF with success exit status
- 0x4 means EOF with error
for example (eof = flag & 0x6) eof will be true for last message u will ever
receive on this callback.
Note: if callback is none, a default callback will be used that prints output on stdout/stderr
based on level.
:return: None
"""
if callback is None:
callback = Response.__default
if not callable(callback):
raise Exception('callback must be callable')
queue = 'stream:%s' % self.id
r = self._client._redis
# we can terminate quickly by checking if the process is not running and it has no queued output.
# if not self.running and r.llen(queue) == 0:
# return
while True:
data = r.blpop(queue, 10)
if data is None:
if not self.running:
break
continue
_, body = data
payload = json.loads(body.decode())
message = payload['message']
line = message['message']
meta = message['meta']
callback(meta >> 16, line, meta & 0xff)
if meta & 0x6 != 0:
break | Runtime copy of job messages. This required the 'stream` flag to be set to True otherwise it will
not be able to copy any output, while it will block until the process exits.
:note: This function will block until it reaches end of stream or the process is no longer running.
:param callback: callback method that will get called for each received message
callback accepts 3 arguments
- level int: the log message levels, refer to the docs for available levels
and their meanings
- message str: the actual output message
- flags int: flags associated with this message
- 0x2 means EOF with success exit status
- 0x4 means EOF with error
for example (eof = flag & 0x6) eof will be true for last message u will ever
receive on this callback.
Note: if callback is none, a default callback will be used that prints output on stdout/stderr
based on level.
:return: None | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L187-L237 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | Response.get | def get(self, timeout=None):
"""
Waits for a job to finish (max of given timeout seconds) and return job results. When a job exits get() will
keep returning the same result until zero-os doesn't remember the job anymore (self.exists == False)
:notes: the timeout here is a client side timeout, it's different than the timeout given to the job on start
(like in system method) witch will cause the job to be killed if it exceeded this timeout.
:param timeout: max time to wait for the job to finish in seconds
:return: Return object
"""
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 JobNotFoundError(self.id)
v = r.brpoplpush(self._queue, self._queue, min(maxwait, 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 TimeoutError() | python | def get(self, timeout=None):
"""
Waits for a job to finish (max of given timeout seconds) and return job results. When a job exits get() will
keep returning the same result until zero-os doesn't remember the job anymore (self.exists == False)
:notes: the timeout here is a client side timeout, it's different than the timeout given to the job on start
(like in system method) witch will cause the job to be killed if it exceeded this timeout.
:param timeout: max time to wait for the job to finish in seconds
:return: Return object
"""
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 JobNotFoundError(self.id)
v = r.brpoplpush(self._queue, self._queue, min(maxwait, 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 TimeoutError() | Waits for a job to finish (max of given timeout seconds) and return job results. When a job exits get() will
keep returning the same result until zero-os doesn't remember the job anymore (self.exists == False)
:notes: the timeout here is a client side timeout, it's different than the timeout given to the job on start
(like in system method) witch will cause the job to be killed if it exceeded this timeout.
:param timeout: max time to wait for the job to finish in seconds
:return: Return object | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L245-L273 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | JSONResponse.get | def get(self, timeout=None):
"""
Get response as json, will fail if the job doesn't return a valid json response
:param timeout: client side timeout in seconds
:return: int
"""
result = super().get(timeout)
if result.state != 'SUCCESS':
raise ResultError(result.data, result.code)
if result.level != 20:
raise ResultError('not a json response: %d' % result.level, 406)
return json.loads(result.data) | python | def get(self, timeout=None):
"""
Get response as json, will fail if the job doesn't return a valid json response
:param timeout: client side timeout in seconds
:return: int
"""
result = super().get(timeout)
if result.state != 'SUCCESS':
raise ResultError(result.data, result.code)
if result.level != 20:
raise ResultError('not a json response: %d' % result.level, 406)
return json.loads(result.data) | Get response as json, will fail if the job doesn't return a valid json response
:param timeout: client side timeout in seconds
:return: int | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L280-L293 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | JobManager.list | 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) | python | 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) | List all running jobs
:param id: optional ID for the job to list | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L372-L380 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | JobManager.kill | 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) | python | 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) | 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 | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L382-L395 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ProcessManager.list | 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) | python | 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) | List all running processes
:param id: optional PID for the process to list | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L411-L419 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | FilesystemManager.open | 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) | python | 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) | 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 | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L442-L464 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | FilesystemManager.move | 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) | python | 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) | Move a path to destination
:param path: source
:param destination: destination
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L516-L529 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | FilesystemManager.chmod | 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) | python | 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) | Change file/dir permission
:param path: path of file/dir to change
:param mode: octet mode
:param recursive: apply chmod recursively
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L531-L546 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | FilesystemManager.chown | 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) | python | 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) | Change file/dir owner
:param path: path of file/dir
:param user: user name
:param group: group name
:param recursive: apply chown recursively
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L548-L565 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | FilesystemManager.read | 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()) | python | 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()) | Read a block from the given file descriptor
:param fd: file descriptor
:return: bytes | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L567-L579 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | FilesystemManager.write | 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) | python | 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) | 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. | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L581-L596 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | FilesystemManager.upload | 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) | python | 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) | Uploads a file
:param remote: remote file name
:param reader: an object that implements the read(size) method (typically a file descriptor)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L610-L624 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | FilesystemManager.download | 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) | python | 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) | Downloads a file
:param remote: remote file name
:param writer: an object the implements the write(bytes) interface (typical a file descriptor)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L626-L640 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | FilesystemManager.upload_file | def upload_file(self, remote, local):
"""
Uploads a file
:param remote: remote file name
:param local: local file name
:return:
"""
file = open(local, 'rb')
try:
self.upload(remote, file)
finally:
file.close() | python | def upload_file(self, remote, local):
"""
Uploads a file
:param remote: remote file name
:param local: local file name
:return:
"""
file = open(local, 'rb')
try:
self.upload(remote, file)
finally:
file.close() | Uploads a file
:param remote: remote file name
:param local: local file name
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L642-L653 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | FilesystemManager.download_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')
try:
self.download(remote, file)
finally:
file.close() | python | def download_file(self, remote, local):
"""
Downloads a file
:param remote: remote file name
:param local: local file name
:return:
"""
file = open(local, 'wb')
try:
self.download(remote, file)
finally:
file.close() | Downloads a file
:param remote: remote file name
:param local: local file name
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L655-L666 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BaseClient.raw | def raw(self, command, arguments, queue=None, max_time=None, stream=False, tags=None, id=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.
:param queue: command queue (commands on the same queue are executed sequentially)
:param max_time: kill job server side if it exceeded this amount of seconds
:param stream: If True, process stdout and stderr are pushed to a special queue (stream:<id>) so
client can stream output
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Response object
"""
raise NotImplemented() | python | def raw(self, command, arguments, queue=None, max_time=None, stream=False, tags=None, id=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.
:param queue: command queue (commands on the same queue are executed sequentially)
:param max_time: kill job server side if it exceeded this amount of seconds
:param stream: If True, process stdout and stderr are pushed to a special queue (stream:<id>) so
client can stream output
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Response object
"""
raise NotImplemented() | 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.
:param queue: command queue (commands on the same queue are executed sequentially)
:param max_time: kill job server side if it exceeded this amount of seconds
:param stream: If True, process stdout and stderr are pushed to a special queue (stream:<id>) so
client can stream output
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Response object | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L734-L750 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BaseClient.sync | def sync(self, command, arguments, tags=None, id=None):
"""
Same as self.raw except it do a response.get() waiting for the command execution to finish and reads the result
: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.
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Result object
"""
response = self.raw(command, arguments, tags=tags, id=id)
result = response.get()
if result.state != 'SUCCESS':
raise ResultError(msg='%s' % result.data, code=result.code)
return result | python | def sync(self, command, arguments, tags=None, id=None):
"""
Same as self.raw except it do a response.get() waiting for the command execution to finish and reads the result
: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.
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Result object
"""
response = self.raw(command, arguments, tags=tags, id=id)
result = response.get()
if result.state != 'SUCCESS':
raise ResultError(msg='%s' % result.data, code=result.code)
return result | Same as self.raw except it do a response.get() waiting for the command execution to finish and reads the result
: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.
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Result object | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L752-L769 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BaseClient.json | def json(self, command, arguments, tags=None, id=None):
"""
Same as self.sync except it assumes the returned result is json, and loads the payload of the return object
if the returned (data) is not of level (20) an error is raised.
:Return: Data
"""
result = self.sync(command, arguments, tags=tags, id=id)
if result.level != 20:
raise RuntimeError('invalid result level, expecting json(20) got (%d)' % result.level)
return json.loads(result.data) | python | def json(self, command, arguments, tags=None, id=None):
"""
Same as self.sync except it assumes the returned result is json, and loads the payload of the return object
if the returned (data) is not of level (20) an error is raised.
:Return: Data
"""
result = self.sync(command, arguments, tags=tags, id=id)
if result.level != 20:
raise RuntimeError('invalid result level, expecting json(20) got (%d)' % result.level)
return json.loads(result.data) | Same as self.sync except it assumes the returned result is json, and loads the payload of the return object
if the returned (data) is not of level (20) an error is raised.
:Return: Data | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L771-L781 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BaseClient.system | def system(self, command, dir='', stdin='', env=None, queue=None, max_time=None, stream=False, tags=None, id=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
:param id: job id. Auto generated if not defined.
: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,
queue=queue, max_time=max_time, stream=stream, tags=tags, id=id)
return response | python | def system(self, command, dir='', stdin='', env=None, queue=None, max_time=None, stream=False, tags=None, id=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
:param id: job id. Auto generated if not defined.
: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,
queue=queue, max_time=max_time, stream=stream, tags=tags, id=id)
return response | 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
:param id: job id. Auto generated if not defined.
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L791-L818 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BaseClient.bash | def bash(self, script, stdin='', queue=None, max_time=None, stream=False, tags=None, id=None):
"""
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
:param id: job id. Auto generated if not defined.
:return:
"""
args = {
'script': script,
'stdin': stdin,
}
self._bash_chk.check(args)
response = self.raw(command='bash', arguments=args,
queue=queue, max_time=max_time, stream=stream, tags=tags, id=id)
return response | python | def bash(self, script, stdin='', queue=None, max_time=None, stream=False, tags=None, id=None):
"""
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
:param id: job id. Auto generated if not defined.
:return:
"""
args = {
'script': script,
'stdin': stdin,
}
self._bash_chk.check(args)
response = self.raw(command='bash', arguments=args,
queue=queue, max_time=max_time, stream=stream, tags=tags, id=id)
return response | 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
:param id: job id. Auto generated if not defined.
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L820-L837 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BaseClient.subscribe | def subscribe(self, job, id=None):
"""
Subscribes to job logs. It return the subscribe Response object which you will need to call .stream() on
to read the output stream of this job.
Calling subscribe multiple times will cause different subscriptions on the same job, each subscription will
have a copy of this job streams.
Note: killing the subscription job will not affect this job, it will also not cause unsubscripe from this stream
the subscriptions will die automatically once this job exits.
example:
job = client.system('long running job')
subscription = client.subscribe(job.id)
subscription.stream() # this will print directly on stdout/stderr check stream docs for more details.
hint: u can give an optional id to the subscriber (otherwise a guid will be generate for you). You probably want
to use this in case your job watcher died, so u can hook on the stream of the current subscriber instead of creating a new one
example:
job = client.system('long running job')
subscription = client.subscribe(job.id, 'my-job-subscriber')
subscription.stream()
# process dies for any reason
# on next start u can simply do
subscription = client.response_for('my-job-subscriber')
subscription.stream()
:param job: the job ID to subscribe to
:param id: the subscriber ID (optional)
:return: the subscribe Job object
"""
return self.raw('core.subscribe', {'id': job}, stream=True, id=id) | python | def subscribe(self, job, id=None):
"""
Subscribes to job logs. It return the subscribe Response object which you will need to call .stream() on
to read the output stream of this job.
Calling subscribe multiple times will cause different subscriptions on the same job, each subscription will
have a copy of this job streams.
Note: killing the subscription job will not affect this job, it will also not cause unsubscripe from this stream
the subscriptions will die automatically once this job exits.
example:
job = client.system('long running job')
subscription = client.subscribe(job.id)
subscription.stream() # this will print directly on stdout/stderr check stream docs for more details.
hint: u can give an optional id to the subscriber (otherwise a guid will be generate for you). You probably want
to use this in case your job watcher died, so u can hook on the stream of the current subscriber instead of creating a new one
example:
job = client.system('long running job')
subscription = client.subscribe(job.id, 'my-job-subscriber')
subscription.stream()
# process dies for any reason
# on next start u can simply do
subscription = client.response_for('my-job-subscriber')
subscription.stream()
:param job: the job ID to subscribe to
:param id: the subscriber ID (optional)
:return: the subscribe Job object
"""
return self.raw('core.subscribe', {'id': job}, stream=True, id=id) | Subscribes to job logs. It return the subscribe Response object which you will need to call .stream() on
to read the output stream of this job.
Calling subscribe multiple times will cause different subscriptions on the same job, each subscription will
have a copy of this job streams.
Note: killing the subscription job will not affect this job, it will also not cause unsubscripe from this stream
the subscriptions will die automatically once this job exits.
example:
job = client.system('long running job')
subscription = client.subscribe(job.id)
subscription.stream() # this will print directly on stdout/stderr check stream docs for more details.
hint: u can give an optional id to the subscriber (otherwise a guid will be generate for you). You probably want
to use this in case your job watcher died, so u can hook on the stream of the current subscriber instead of creating a new one
example:
job = client.system('long running job')
subscription = client.subscribe(job.id, 'my-job-subscriber')
subscription.stream()
# process dies for any reason
# on next start u can simply do
subscription = client.response_for('my-job-subscriber')
subscription.stream()
:param job: the job ID to subscribe to
:param id: the subscriber ID (optional)
:return: the subscribe Job object | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L839-L876 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ContainerClient.raw | def raw(self, command, arguments, queue=None, max_time=None, stream=False, tags=None, id=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.
:param queue: command queue (commands on the same queue are executed sequentially)
:param max_time: kill job server side if it exceeded this amount of seconds
:param stream: If True, process stdout and stderr are pushed to a special queue (stream:<id>) so
client can stream output
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Response object
"""
args = {
'container': self._container,
'command': {
'command': command,
'arguments': arguments,
'queue': queue,
'max_time': max_time,
'stream': stream,
'tags': tags,
'id': id,
},
}
# 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) | python | def raw(self, command, arguments, queue=None, max_time=None, stream=False, tags=None, id=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.
:param queue: command queue (commands on the same queue are executed sequentially)
:param max_time: kill job server side if it exceeded this amount of seconds
:param stream: If True, process stdout and stderr are pushed to a special queue (stream:<id>) so
client can stream output
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Response object
"""
args = {
'container': self._container,
'command': {
'command': command,
'arguments': arguments,
'queue': queue,
'max_time': max_time,
'stream': stream,
'tags': tags,
'id': id,
},
}
# 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) | 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.
:param queue: command queue (commands on the same queue are executed sequentially)
:param max_time: kill job server side if it exceeded this amount of seconds
:param stream: If True, process stdout and stderr are pushed to a special queue (stream:<id>) so
client can stream output
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Response object | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L927-L966 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ContainerManager.create | def create(self, root_url, mount=None, host_network=False, nics=DefaultNetworking, port=None,
hostname=None, privileged=False, storage=None, name=None, tags=None, identity=None, env=None,
cgroups=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 # one of default, bridge, zerotier, macvlan, passthrough, vlan, or vxlan (note, vlan and vxlan only supported by ovs)
'id': id # depends on the type
bridge: bridge name,
zerotier: network id,
macvlan: the parent link name,
passthrough: the link name,
vlan: the vlan tag,
vxlan: 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.
:param name: Optional name for the container
:param identity: Container Zerotier identity, Only used if at least one of the nics is of type zerotier
:param env: a dict with the environment variables needed to be set for the container
:param cgroups: custom list of cgroups to apply to this container on creation. formated as [(subsystem, name), ...]
please refer to the cgroup api for more detailes.
"""
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,
'name': name,
'identity': identity,
'env': env,
'cgroups': cgroups,
}
# validate input
self._create_chk.check(args)
response = self._client.raw('corex.create', args, tags=tags)
return JSONResponse(response) | python | def create(self, root_url, mount=None, host_network=False, nics=DefaultNetworking, port=None,
hostname=None, privileged=False, storage=None, name=None, tags=None, identity=None, env=None,
cgroups=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 # one of default, bridge, zerotier, macvlan, passthrough, vlan, or vxlan (note, vlan and vxlan only supported by ovs)
'id': id # depends on the type
bridge: bridge name,
zerotier: network id,
macvlan: the parent link name,
passthrough: the link name,
vlan: the vlan tag,
vxlan: 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.
:param name: Optional name for the container
:param identity: Container Zerotier identity, Only used if at least one of the nics is of type zerotier
:param env: a dict with the environment variables needed to be set for the container
:param cgroups: custom list of cgroups to apply to this container on creation. formated as [(subsystem, name), ...]
please refer to the cgroup api for more detailes.
"""
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,
'name': name,
'identity': identity,
'env': env,
'cgroups': cgroups,
}
# validate input
self._create_chk.check(args)
response = self._client.raw('corex.create', args, tags=tags)
return JSONResponse(response) | 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 # one of default, bridge, zerotier, macvlan, passthrough, vlan, or vxlan (note, vlan and vxlan only supported by ovs)
'id': id # depends on the type
bridge: bridge name,
zerotier: network id,
macvlan: the parent link name,
passthrough: the link name,
vlan: the vlan tag,
vxlan: 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.
:param name: Optional name for the container
:param identity: Container Zerotier identity, Only used if at least one of the nics is of type zerotier
:param env: a dict with the environment variables needed to be set for the container
:param cgroups: custom list of cgroups to apply to this container on creation. formated as [(subsystem, name), ...]
please refer to the cgroup api for more detailes. | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1034-L1108 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ContainerManager.find | 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}) | python | 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}) | Find containers that matches set of tags
:param tags:
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1117-L1124 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ContainerManager.terminate | def terminate(self, container):
"""
Terminate a container given it's id
:param container: container id
:return:
"""
self._client_chk.check(container)
args = {
'container': int(container),
}
response = self._client.raw('corex.terminate', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to terminate container: %s' % result.data) | python | def terminate(self, container):
"""
Terminate a container given it's id
:param container: container id
:return:
"""
self._client_chk.check(container)
args = {
'container': int(container),
}
response = self._client.raw('corex.terminate', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError('failed to terminate container: %s' % result.data) | Terminate a container given it's id
:param container: container id
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1126-L1141 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ContainerManager.nic_add | def nic_add(self, container, nic):
"""
Hot plug a nic into a container
:param container: container ID
:param nic: {
'type': nic_type # one of default, bridge, zerotier, macvlan, passthrough, vlan, or vxlan (note, vlan and vxlan only supported by ovs)
'id': id # depends on the type
bridge: bridge name,
zerotier: network id,
macvlan: the parent link name,
passthrough: the link name,
vlan: the vlan tag,
vxlan: 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]
}
}
:return:
"""
args = {
'container': container,
'nic': nic
}
self._nic_add.check(args)
return self._client.json('corex.nic-add', args) | python | def nic_add(self, container, nic):
"""
Hot plug a nic into a container
:param container: container ID
:param nic: {
'type': nic_type # one of default, bridge, zerotier, macvlan, passthrough, vlan, or vxlan (note, vlan and vxlan only supported by ovs)
'id': id # depends on the type
bridge: bridge name,
zerotier: network id,
macvlan: the parent link name,
passthrough: the link name,
vlan: the vlan tag,
vxlan: 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]
}
}
:return:
"""
args = {
'container': container,
'nic': nic
}
self._nic_add.check(args)
return self._client.json('corex.nic-add', args) | Hot plug a nic into a container
:param container: container ID
:param nic: {
'type': nic_type # one of default, bridge, zerotier, macvlan, passthrough, vlan, or vxlan (note, vlan and vxlan only supported by ovs)
'id': id # depends on the type
bridge: bridge name,
zerotier: network id,
macvlan: the parent link name,
passthrough: the link name,
vlan: the vlan tag,
vxlan: 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]
}
}
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1143-L1174 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ContainerManager.nic_remove | def nic_remove(self, container, index):
"""
Hot unplug of nic from a container
Note: removing a nic, doesn't remove the nic from the container info object, instead it sets it's state
to `destroyed`.
:param container: container ID
:param index: index of the nic as returned in the container object info (as shown by container.list())
:return:
"""
args = {
'container': container,
'index': index
}
self._nic_remove.check(args)
return self._client.json('corex.nic-remove', args) | python | def nic_remove(self, container, index):
"""
Hot unplug of nic from a container
Note: removing a nic, doesn't remove the nic from the container info object, instead it sets it's state
to `destroyed`.
:param container: container ID
:param index: index of the nic as returned in the container object info (as shown by container.list())
:return:
"""
args = {
'container': container,
'index': index
}
self._nic_remove.check(args)
return self._client.json('corex.nic-remove', args) | Hot unplug of nic from a container
Note: removing a nic, doesn't remove the nic from the container info object, instead it sets it's state
to `destroyed`.
:param container: container ID
:param index: index of the nic as returned in the container object info (as shown by container.list())
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1176-L1193 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ContainerManager.client | 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 a ContainerResponse from container.create
"""
self._client_chk.check(container)
return ContainerClient(self._client, int(container)) | python | 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 a ContainerResponse from container.create
"""
self._client_chk.check(container)
return ContainerClient(self._client, int(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 a ContainerResponse from container.create | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1195-L1205 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ContainerManager.backup | def backup(self, container, url):
"""
Backup a container to the given restic url
all restic urls are supported
:param container:
:param url: Url to restic repo
examples
(file:///path/to/restic/?password=<password>)
:return: Json response to the backup job (do .get() to get the snapshot ID
"""
args = {
'container': container,
'url': url,
}
return JSONResponse(self._client.raw('corex.backup', args)) | python | def backup(self, container, url):
"""
Backup a container to the given restic url
all restic urls are supported
:param container:
:param url: Url to restic repo
examples
(file:///path/to/restic/?password=<password>)
:return: Json response to the backup job (do .get() to get the snapshot ID
"""
args = {
'container': container,
'url': url,
}
return JSONResponse(self._client.raw('corex.backup', args)) | Backup a container to the given restic url
all restic urls are supported
:param container:
:param url: Url to restic repo
examples
(file:///path/to/restic/?password=<password>)
:return: Json response to the backup job (do .get() to get the snapshot ID | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1207-L1225 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ContainerManager.restore | def restore(self, url, tags=None):
"""
Full restore of a container backup. This restore method will recreate
an exact copy of the backedup container (including same network setup, and other
configurations as defined by the `create` method.
To just restore the container data, and use new configuration, use the create method instead
with the `root_url` set to `restic:<url>`
:param url: Snapshot url, the snapshot ID is passed as a url fragment
examples:
`file:///path/to/restic/repo?password=<password>#<snapshot-id>`
:param tags: this will always override the original container tags (even if not set)
:return:
"""
args = {
'url': url,
}
return JSONResponse(self._client.raw('corex.restore', args, tags=tags)) | python | def restore(self, url, tags=None):
"""
Full restore of a container backup. This restore method will recreate
an exact copy of the backedup container (including same network setup, and other
configurations as defined by the `create` method.
To just restore the container data, and use new configuration, use the create method instead
with the `root_url` set to `restic:<url>`
:param url: Snapshot url, the snapshot ID is passed as a url fragment
examples:
`file:///path/to/restic/repo?password=<password>#<snapshot-id>`
:param tags: this will always override the original container tags (even if not set)
:return:
"""
args = {
'url': url,
}
return JSONResponse(self._client.raw('corex.restore', args, tags=tags)) | Full restore of a container backup. This restore method will recreate
an exact copy of the backedup container (including same network setup, and other
configurations as defined by the `create` method.
To just restore the container data, and use new configuration, use the create method instead
with the `root_url` set to `restic:<url>`
:param url: Snapshot url, the snapshot ID is passed as a url fragment
examples:
`file:///path/to/restic/repo?password=<password>#<snapshot-id>`
:param tags: this will always override the original container tags (even if not set)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1227-L1246 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BridgeManager.create | 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)
return self._client.json('bridge.create', args) | python | 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)
return self._client.json('bridge.create', args) | 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. | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1520-L1554 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BridgeManager.delete | def delete(self, bridge):
"""
Delete a bridge by name
:param bridge: bridge name
:return:
"""
args = {
'name': bridge,
}
self._bridge_chk.check(args)
return self._client.json('bridge.delete', args) | python | def delete(self, bridge):
"""
Delete a bridge by name
:param bridge: bridge name
:return:
"""
args = {
'name': bridge,
}
self._bridge_chk.check(args)
return self._client.json('bridge.delete', args) | Delete a bridge by name
:param bridge: bridge name
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1563-L1576 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BridgeManager.nic_add | def nic_add(self, bridge, nic):
"""
Attach a nic to a bridge
:param bridge: bridge name
:param nic: nic name
"""
args = {
'name': bridge,
'nic': nic,
}
self._nic_add_chk.check(args)
return self._client.json('bridge.nic-add', args) | python | def nic_add(self, bridge, nic):
"""
Attach a nic to a bridge
:param bridge: bridge name
:param nic: nic name
"""
args = {
'name': bridge,
'nic': nic,
}
self._nic_add_chk.check(args)
return self._client.json('bridge.nic-add', args) | Attach a nic to a bridge
:param bridge: bridge name
:param nic: nic name | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1578-L1593 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BridgeManager.nic_remove | def nic_remove(self, nic):
"""
Detach a nic from a bridge
:param nic: nic name to detach
"""
args = {
'nic': nic,
}
self._nic_remove_chk.check(args)
return self._client.json('bridge.nic-remove', args) | python | def nic_remove(self, nic):
"""
Detach a nic from a bridge
:param nic: nic name to detach
"""
args = {
'nic': nic,
}
self._nic_remove_chk.check(args)
return self._client.json('bridge.nic-remove', args) | Detach a nic from a bridge
:param nic: nic name to detach | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1595-L1608 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BridgeManager.nic_list | def nic_list(self, bridge):
"""
List nics attached to bridge
:param bridge: bridge name
"""
args = {
'name': bridge,
}
self._bridge_chk.check(args)
return self._client.json('bridge.nic-list', args) | python | def nic_list(self, bridge):
"""
List nics attached to bridge
:param bridge: bridge name
"""
args = {
'name': bridge,
}
self._bridge_chk.check(args)
return self._client.json('bridge.nic-list', args) | List nics attached to bridge
:param bridge: bridge name | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1610-L1623 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | DiskManager.list | 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 {} | python | 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 {} | List available block devices | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1670-L1688 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | DiskManager.mktable | def mktable(self, disk, table_type='gpt'):
"""
Make partition table on block device.
:param disk: device path (/dev/sda, /dev/disk/by-id/ata-Samsung..., 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) | python | def mktable(self, disk, table_type='gpt'):
"""
Make partition table on block device.
:param disk: device path (/dev/sda, /dev/disk/by-id/ata-Samsung..., 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) | Make partition table on block device.
:param disk: device path (/dev/sda, /dev/disk/by-id/ata-Samsung..., etc...)
:param table_type: Partition table type as accepted by parted | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1690-L1708 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | DiskManager.getinfo | def getinfo(self, disk, part=''):
"""
Get more info about a disk or a disk partition
:param disk: (/dev/sda, /dev/sdb, etc..)
:param part: (/dev/sda1, /dev/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 {} | python | def getinfo(self, disk, part=''):
"""
Get more info about a disk or a disk partition
:param disk: (/dev/sda, /dev/sdb, etc..)
:param part: (/dev/sda1, /dev/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 {} | Get more info about a disk or a disk partition
:param disk: (/dev/sda, /dev/sdb, etc..)
:param part: (/dev/sda1, /dev/sdb2, etc...)
:return: a dict with {"blocksize", "start", "size", and "free" sections} | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1710-L1739 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | DiskManager.mkpart | def mkpart(self, disk, start, end, part_type='primary'):
"""
Make partition on disk
:param disk: device path (/dev/sda, /dev/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) | python | def mkpart(self, disk, start, end, part_type='primary'):
"""
Make partition on disk
:param disk: device path (/dev/sda, /dev/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) | Make partition on disk
:param disk: device path (/dev/sda, /dev/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 | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1741-L1763 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | DiskManager.rmpart | def rmpart(self, disk, number):
"""
Remove partion from disk
:param disk: device path (/dev/sda, /dev/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) | python | def rmpart(self, disk, number):
"""
Remove partion from disk
:param disk: device path (/dev/sda, /dev/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) | Remove partion from disk
:param disk: device path (/dev/sda, /dev/sdb, etc...)
:param number: Partition number (starting from 1) | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1765-L1783 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | DiskManager.mount | 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) | python | 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) | Mount partion on target
:param source: Full partition path like /dev/sda1
:param target: Mount point
:param options: Optional mount options | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1785-L1808 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | DiskManager.umount | 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) | python | 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) | Unmount partion
:param source: Full partition path like /dev/sda1 | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1810-L1826 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | DiskManager.spindown | def spindown(self, disk, spindown=1):
"""
Spindown a disk
:param disk str: Full path to a disk like /dev/sda
:param spindown int: spindown value should be in [1, 240]
"""
args = {
"disk": disk,
"spindown": spindown
}
self._spindown_chk.check(args)
response = self._client.raw('disk.spindown', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError("Failed to spindown disk {} to {}.".format(disk, spindown)) | python | def spindown(self, disk, spindown=1):
"""
Spindown a disk
:param disk str: Full path to a disk like /dev/sda
:param spindown int: spindown value should be in [1, 240]
"""
args = {
"disk": disk,
"spindown": spindown
}
self._spindown_chk.check(args)
response = self._client.raw('disk.spindown', args)
result = response.get()
if result.state != 'SUCCESS':
raise RuntimeError("Failed to spindown disk {} to {}.".format(disk, spindown)) | Spindown a disk
:param disk str: Full path to a disk like /dev/sda
:param spindown int: spindown value should be in [1, 240] | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1828-L1843 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | DiskManager.seektime | def seektime(self, disk):
"""
Gives seek latency on disk which is a very good indication to the `type` of the disk.
it's a very good way to verify if the underlying disk type is SSD or HDD
:param disk: disk path or name (/dev/sda, or sda)
:return: a dict as follows {'device': '<device-path>', 'elapsed': <seek-time in us', 'type': '<SSD or HDD>'}
"""
args = {
'disk': disk,
}
self._seektime_chk.check(args)
return self._client.json("disk.seektime", args) | python | def seektime(self, disk):
"""
Gives seek latency on disk which is a very good indication to the `type` of the disk.
it's a very good way to verify if the underlying disk type is SSD or HDD
:param disk: disk path or name (/dev/sda, or sda)
:return: a dict as follows {'device': '<device-path>', 'elapsed': <seek-time in us', 'type': '<SSD or HDD>'}
"""
args = {
'disk': disk,
}
self._seektime_chk.check(args)
return self._client.json("disk.seektime", args) | Gives seek latency on disk which is a very good indication to the `type` of the disk.
it's a very good way to verify if the underlying disk type is SSD or HDD
:param disk: disk path or name (/dev/sda, or sda)
:return: a dict as follows {'device': '<device-path>', 'elapsed': <seek-time in us', 'type': '<SSD or HDD>'} | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1845-L1859 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BtrfsManager.create | 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) | python | 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) | 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 | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1906-L1925 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BtrfsManager.device_add | 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) | python | 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) | 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: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1927-L1945 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BtrfsManager.subvol_create | 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) | python | 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) | Create a btrfs subvolume in the specified path
:param path: path to create | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1967-L1976 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BtrfsManager.subvol_delete | 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) | python | 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) | Delete a btrfs subvolume in the specified path
:param path: path to delete | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1987-L1998 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BtrfsManager.subvol_quota | 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) | python | 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) | 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 | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2000-L2013 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | BtrfsManager.subvol_snapshot | 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) | python | 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) | 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: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2015-L2032 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | ZerotierManager.join | 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) | python | 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) | Join a zerotier network
:param network: network id to join
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2043-L2056 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.create | def create(self, name, media=None, flist=None, cpu=2, memory=512,
nics=None, port=None, mount=None, tags=None, config=None):
"""
:param name: Name of the kvm domain
:param media: (optional) 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', 'url: '/somefile.iso'}]
zdb exmpale:
[{'url': 'zdb://host:port?size=10G&blocksize=4096'},
{'url': 'zdb+unix:///path/to/unix.socket?size=5G'}]
:param flist: (optional) VM flist. A special bootable flist witch has a correct boot.yaml file
example: http://hub.gig.tech/azmy/ubuntu-zesty.flist
: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
}
:param port: Configure port forwards to vm, this only works if default network nic is added. Is a dict of {host-port: guest-port}
:param mount: A list of host shared folders in the format {'source': '/host/path', 'target': '/guest/path', 'readonly': True|False}
:param tags: A list of user defined tags (strings)
:param config: a map with the config file path as a key and content as a value. This only works when creating a VM from an flist. The
config files are written to the machine before booting.
Example:
config = {'/root/.ssh/authorized_keys': '<PUBLIC KEYS>'}
If the machine is not booted from an flist, the config are discarded
:note: At least one media or an flist must be provided.
:return: uuid of the virtual machine
"""
if nics is None:
nics = []
args = {
'name': name,
'media': media,
'cpu': cpu,
'flist': flist,
'memory': memory,
'nics': nics,
'port': port,
'mount': mount,
'tags': tags,
'config': config,
}
self._create_chk.check(args)
if media is None and flist is None:
raise ValueError('need at least one boot media via media or an flist')
return self._client.json('kvm.create', args, tags=tags) | python | def create(self, name, media=None, flist=None, cpu=2, memory=512,
nics=None, port=None, mount=None, tags=None, config=None):
"""
:param name: Name of the kvm domain
:param media: (optional) 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', 'url: '/somefile.iso'}]
zdb exmpale:
[{'url': 'zdb://host:port?size=10G&blocksize=4096'},
{'url': 'zdb+unix:///path/to/unix.socket?size=5G'}]
:param flist: (optional) VM flist. A special bootable flist witch has a correct boot.yaml file
example: http://hub.gig.tech/azmy/ubuntu-zesty.flist
: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
}
:param port: Configure port forwards to vm, this only works if default network nic is added. Is a dict of {host-port: guest-port}
:param mount: A list of host shared folders in the format {'source': '/host/path', 'target': '/guest/path', 'readonly': True|False}
:param tags: A list of user defined tags (strings)
:param config: a map with the config file path as a key and content as a value. This only works when creating a VM from an flist. The
config files are written to the machine before booting.
Example:
config = {'/root/.ssh/authorized_keys': '<PUBLIC KEYS>'}
If the machine is not booted from an flist, the config are discarded
:note: At least one media or an flist must be provided.
:return: uuid of the virtual machine
"""
if nics is None:
nics = []
args = {
'name': name,
'media': media,
'cpu': cpu,
'flist': flist,
'memory': memory,
'nics': nics,
'port': port,
'mount': mount,
'tags': tags,
'config': config,
}
self._create_chk.check(args)
if media is None and flist is None:
raise ValueError('need at least one boot media via media or an flist')
return self._client.json('kvm.create', args, tags=tags) | :param name: Name of the kvm domain
:param media: (optional) 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', 'url: '/somefile.iso'}]
zdb exmpale:
[{'url': 'zdb://host:port?size=10G&blocksize=4096'},
{'url': 'zdb+unix:///path/to/unix.socket?size=5G'}]
:param flist: (optional) VM flist. A special bootable flist witch has a correct boot.yaml file
example: http://hub.gig.tech/azmy/ubuntu-zesty.flist
: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
}
:param port: Configure port forwards to vm, this only works if default network nic is added. Is a dict of {host-port: guest-port}
:param mount: A list of host shared folders in the format {'source': '/host/path', 'target': '/guest/path', 'readonly': True|False}
:param tags: A list of user defined tags (strings)
:param config: a map with the config file path as a key and content as a value. This only works when creating a VM from an flist. The
config files are written to the machine before booting.
Example:
config = {'/root/.ssh/authorized_keys': '<PUBLIC KEYS>'}
If the machine is not booted from an flist, the config are discarded
:note: At least one media or an flist must be provided.
:return: uuid of the virtual machine | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2224-L2282 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.prepare_migration_target | def prepare_migration_target(self, uuid, nics=None, port=None, tags=None):
"""
:param name: Name of the kvm domain that will be migrated
: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
}
:param uuid: uuid of machine to be migrated on old node
:return:
"""
if nics is None:
nics = []
args = {
'nics': nics,
'port': port,
'uuid': uuid
}
self._migrate_network_chk.check(args)
self._client.sync('kvm.prepare_migration_target', args, tags=tags) | python | def prepare_migration_target(self, uuid, nics=None, port=None, tags=None):
"""
:param name: Name of the kvm domain that will be migrated
: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
}
:param uuid: uuid of machine to be migrated on old node
:return:
"""
if nics is None:
nics = []
args = {
'nics': nics,
'port': port,
'uuid': uuid
}
self._migrate_network_chk.check(args)
self._client.sync('kvm.prepare_migration_target', args, tags=tags) | :param name: Name of the kvm domain that will be migrated
: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
}
:param uuid: uuid of machine to be migrated on old node
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2284-L2311 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.destroy | 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) | python | 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) | Destroy a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2313-L2324 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.shutdown | 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) | python | 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) | Shutdown a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2326-L2337 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.reboot | 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) | python | 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) | Reboot a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2339-L2350 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.reset | 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) | python | 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) | Reset (Force reboot) a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2352-L2363 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.pause | 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) | python | 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) | Pause a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2365-L2376 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.resume | 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) | python | 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) | Resume a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2378-L2389 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.info | 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) | python | 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) | Get info about a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2391-L2402 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.infops | 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) | python | 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) | Get info per second about a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2404-L2415 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.attach_disk | 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) | python | 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) | 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: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2417-L2432 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.add_nic | 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) | python | 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) | 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: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2451-L2468 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.limit_disk_io | 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) | python | 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) | 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: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2489-L2549 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.migrate | 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) | python | 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) | 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: | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2551-L2564 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | KvmManager.get | def get(self, uuid):
"""
Get machine info
:param uuid str: domain uuid
:return: machine info
"""
args = {'uuid':uuid}
self._get_chk.check(args)
return self._client.json('kvm.get', args) | python | def get(self, uuid):
"""
Get machine info
:param uuid str: domain uuid
:return: machine info
"""
args = {'uuid':uuid}
self._get_chk.check(args)
return self._client.json('kvm.get', args) | Get machine info
:param uuid str: domain uuid
:return: machine info | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2574-L2583 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | Logger.set_level | def set_level(self, level):
"""
Set the log level of the g8os
Note: this level is for messages that ends up on screen or on log file
: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) | python | def set_level(self, level):
"""
Set the log level of the g8os
Note: this level is for messages that ends up on screen or on log file
: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) | Set the log level of the g8os
Note: this level is for messages that ends up on screen or on log file
:param level: the level to be set can be one of ("CRITICAL", "ERROR", "WARNING", "NOTICE", "INFO", "DEBUG") | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2598-L2610 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | Logger.subscribe | def subscribe(self, queue=None, *levels):
"""
Subscribe to the aggregated log stream. On subscribe a ledis queue will be fed with all running processes
logs. Always use the returned queue name from this method, even if u specified the queue name to use
Note: it is legal to subscribe to the same queue, but would be a bad logic if two processes are trying to
read from the same queue.
:param queue: Your unique queue name, otherwise, a one will get generated for your
:param levels:
:return: queue name to pull from
"""
args = {
'queue': queue,
'levels': list(levels),
}
self._subscribe_chk.check(args)
return self._client.json('logger.subscribe', args) | python | def subscribe(self, queue=None, *levels):
"""
Subscribe to the aggregated log stream. On subscribe a ledis queue will be fed with all running processes
logs. Always use the returned queue name from this method, even if u specified the queue name to use
Note: it is legal to subscribe to the same queue, but would be a bad logic if two processes are trying to
read from the same queue.
:param queue: Your unique queue name, otherwise, a one will get generated for your
:param levels:
:return: queue name to pull from
"""
args = {
'queue': queue,
'levels': list(levels),
}
self._subscribe_chk.check(args)
return self._client.json('logger.subscribe', args) | Subscribe to the aggregated log stream. On subscribe a ledis queue will be fed with all running processes
logs. Always use the returned queue name from this method, even if u specified the queue name to use
Note: it is legal to subscribe to the same queue, but would be a bad logic if two processes are trying to
read from the same queue.
:param queue: Your unique queue name, otherwise, a one will get generated for your
:param levels:
:return: queue name to pull from | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2618-L2637 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | Nft.drop_port | 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) | python | 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) | 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 | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2677-L2691 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | AggregatorManager.query | def query(self, key=None, **tags):
"""
Query zero-os aggregator for current state object of monitored metrics.
Note: ID is returned as part of the key (if set) to avoid conflict with similar metrics that
has same key. For example, a cpu core nr can be the id associated with 'machine.CPU.percent'
so we can return all values for all the core numbers in the same dict.
U can filter on the ID as a tag
:example:
self.query(key=key, id=value)
:param key: metric key (ex: machine.memory.ram.available)
:param tags: optional tags filter
:return: dict of {
'key[/id]': state object
}
"""
args = {
'key': key,
'tags': tags,
}
self._query_chk.check(args)
return self._client.json('aggregator.query', args) | python | def query(self, key=None, **tags):
"""
Query zero-os aggregator for current state object of monitored metrics.
Note: ID is returned as part of the key (if set) to avoid conflict with similar metrics that
has same key. For example, a cpu core nr can be the id associated with 'machine.CPU.percent'
so we can return all values for all the core numbers in the same dict.
U can filter on the ID as a tag
:example:
self.query(key=key, id=value)
:param key: metric key (ex: machine.memory.ram.available)
:param tags: optional tags filter
:return: dict of {
'key[/id]': state object
}
"""
args = {
'key': key,
'tags': tags,
}
self._query_chk.check(args)
return self._client.json('aggregator.query', args) | Query zero-os aggregator for current state object of monitored metrics.
Note: ID is returned as part of the key (if set) to avoid conflict with similar metrics that
has same key. For example, a cpu core nr can be the id associated with 'machine.CPU.percent'
so we can return all values for all the core numbers in the same dict.
U can filter on the ID as a tag
:example:
self.query(key=key, id=value)
:param key: metric key (ex: machine.memory.ram.available)
:param tags: optional tags filter
:return: dict of {
'key[/id]': state object
} | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2737-L2761 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | RTInfoManager.start | def start(self, host="localhost", port=8999, disks=None):
"""
Start rtinfo-client
:param host: str rtinfod host address
:param port: int rtinfod client port
:param disks: list of prefixes of wathable disks (e.g ["sd"])
"""
disks = [] if disks is None else disks
args = {
"host": host,
"port": port,
"disks": disks
}
self._rtinfo_start_params_chk.check(args)
return self._client.json("rtinfo.start", args) | python | def start(self, host="localhost", port=8999, disks=None):
"""
Start rtinfo-client
:param host: str rtinfod host address
:param port: int rtinfod client port
:param disks: list of prefixes of wathable disks (e.g ["sd"])
"""
disks = [] if disks is None else disks
args = {
"host": host,
"port": port,
"disks": disks
}
self._rtinfo_start_params_chk.check(args)
return self._client.json("rtinfo.start", args) | Start rtinfo-client
:param host: str rtinfod host address
:param port: int rtinfod client port
:param disks: list of prefixes of wathable disks (e.g ["sd"]) | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2778-L2795 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | RTInfoManager.stop | def stop(self, host, port):
"""
Stop rtinfo-client
:param host: str rtinfod host address
:param port: int rtinfod client port
"""
args = {
"host": host,
"port": port,
}
self._rtinfo_stop_params_chk.check(args)
return self._client.json("rtinfo.stop", args) | python | def stop(self, host, port):
"""
Stop rtinfo-client
:param host: str rtinfod host address
:param port: int rtinfod client port
"""
args = {
"host": host,
"port": port,
}
self._rtinfo_stop_params_chk.check(args)
return self._client.json("rtinfo.stop", args) | Stop rtinfo-client
:param host: str rtinfod host address
:param port: int rtinfod client port | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2797-L2810 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | CGroupManager.ensure | def ensure(self, subsystem, name):
"""
Creates a cgroup if it doesn't exist under the specified subsystem
and the given name
:param subsystem: the cgroup subsystem (currently support 'memory', and 'cpuset')
:param name: name of the cgroup to delete
"""
args = {
'subsystem': subsystem,
'name': name,
}
self._cgroup_chk.check(args)
return self._client.json('cgroup.ensure', args) | python | def ensure(self, subsystem, name):
"""
Creates a cgroup if it doesn't exist under the specified subsystem
and the given name
:param subsystem: the cgroup subsystem (currently support 'memory', and 'cpuset')
:param name: name of the cgroup to delete
"""
args = {
'subsystem': subsystem,
'name': name,
}
self._cgroup_chk.check(args)
return self._client.json('cgroup.ensure', args) | Creates a cgroup if it doesn't exist under the specified subsystem
and the given name
:param subsystem: the cgroup subsystem (currently support 'memory', and 'cpuset')
:param name: name of the cgroup to delete | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2854-L2868 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | CGroupManager.task_add | def task_add(self, subsystem, name, pid):
"""
Add process (with pid) to a cgroup
:param subsystem: the cgroup subsystem (currently support 'memory', and 'cpuset')
:param name: name of the cgroup
:param pid: PID to add
"""
args = {
'subsystem': subsystem,
'name': name,
'pid': pid,
}
self._task_chk.check(args)
return self._client.json('cgroup.task-add', args) | python | def task_add(self, subsystem, name, pid):
"""
Add process (with pid) to a cgroup
:param subsystem: the cgroup subsystem (currently support 'memory', and 'cpuset')
:param name: name of the cgroup
:param pid: PID to add
"""
args = {
'subsystem': subsystem,
'name': name,
'pid': pid,
}
self._task_chk.check(args)
return self._client.json('cgroup.task-add', args) | Add process (with pid) to a cgroup
:param subsystem: the cgroup subsystem (currently support 'memory', and 'cpuset')
:param name: name of the cgroup
:param pid: PID to add | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2902-L2918 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | CGroupManager.memory | def memory(self, name, mem=0, swap=0):
"""
Set/Get memory cgroup specification/limitation
the call to this method will always GET the current set values for both mem and swap.
If mem is not zero, the memory will set the memory limit to the given value, and swap to the given value (even 0)
:param mem: Set memory limit to the given value (in bytes), ignore if 0
:param swap: Set swap limit to the given value (in bytes) (only if mem is not zero)
:return: current memory limitation
"""
args = {
'name': name,
'mem': mem,
'swap': swap,
}
self._memory_spec.check(args)
return self._client.json('cgroup.memory.spec', args) | python | def memory(self, name, mem=0, swap=0):
"""
Set/Get memory cgroup specification/limitation
the call to this method will always GET the current set values for both mem and swap.
If mem is not zero, the memory will set the memory limit to the given value, and swap to the given value (even 0)
:param mem: Set memory limit to the given value (in bytes), ignore if 0
:param swap: Set swap limit to the given value (in bytes) (only if mem is not zero)
:return: current memory limitation
"""
args = {
'name': name,
'mem': mem,
'swap': swap,
}
self._memory_spec.check(args)
return self._client.json('cgroup.memory.spec', args) | Set/Get memory cgroup specification/limitation
the call to this method will always GET the current set values for both mem and swap.
If mem is not zero, the memory will set the memory limit to the given value, and swap to the given value (even 0)
:param mem: Set memory limit to the given value (in bytes), ignore if 0
:param swap: Set swap limit to the given value (in bytes) (only if mem is not zero)
:return: current memory limitation | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2954-L2973 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | CGroupManager.cpuset | def cpuset(self, name, cpus=None, mems=None):
"""
Set/Get cpuset cgroup specification/limitation
the call to this method will always GET the current set values for both cpus and mems
If cpus, or mems is NOT NONE value it will be set as the spec for that attribute
:param cpus: Set cpus affinity limit to the given value (0, 1, 0-10, etc...)
:param mems: Set mems affinity limit to the given value (0, 1, 0-10, etc...)
:return: current cpuset
"""
args = {
'name': name,
'cpus': cpus,
'mems': mems,
}
self._cpuset_spec.check(args)
return self._client.json('cgroup.cpuset.spec', args) | python | def cpuset(self, name, cpus=None, mems=None):
"""
Set/Get cpuset cgroup specification/limitation
the call to this method will always GET the current set values for both cpus and mems
If cpus, or mems is NOT NONE value it will be set as the spec for that attribute
:param cpus: Set cpus affinity limit to the given value (0, 1, 0-10, etc...)
:param mems: Set mems affinity limit to the given value (0, 1, 0-10, etc...)
:return: current cpuset
"""
args = {
'name': name,
'cpus': cpus,
'mems': mems,
}
self._cpuset_spec.check(args)
return self._client.json('cgroup.cpuset.spec', args) | Set/Get cpuset cgroup specification/limitation
the call to this method will always GET the current set values for both cpus and mems
If cpus, or mems is NOT NONE value it will be set as the spec for that attribute
:param cpus: Set cpus affinity limit to the given value (0, 1, 0-10, etc...)
:param mems: Set mems affinity limit to the given value (0, 1, 0-10, etc...)
:return: current cpuset | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2975-L2994 |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | Client.raw | def raw(self, command, arguments, queue=None, max_time=None, stream=False, tags=None, id=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.
:param queue: command queue (commands on the same queue are executed sequentially)
:param max_time: kill job server side if it exceeded this amount of seconds
:param stream: If True, process stdout and stderr are pushed to a special queue (stream:<id>) so
client can stream output
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Response object
"""
if not id:
id = str(uuid.uuid4())
payload = {
'id': id,
'command': command,
'arguments': arguments,
'queue': queue,
'max_time': max_time,
'stream': stream,
'tags': tags,
}
self._raw_chk.check(payload)
flag = 'result:{}:flag'.format(id)
self._redis.rpush('core:default', json.dumps(payload))
if self._redis.brpoplpush(flag, flag, DefaultTimeout) is None:
TimeoutError('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) | python | def raw(self, command, arguments, queue=None, max_time=None, stream=False, tags=None, id=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.
:param queue: command queue (commands on the same queue are executed sequentially)
:param max_time: kill job server side if it exceeded this amount of seconds
:param stream: If True, process stdout and stderr are pushed to a special queue (stream:<id>) so
client can stream output
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Response object
"""
if not id:
id = str(uuid.uuid4())
payload = {
'id': id,
'command': command,
'arguments': arguments,
'queue': queue,
'max_time': max_time,
'stream': stream,
'tags': tags,
}
self._raw_chk.check(payload)
flag = 'result:{}:flag'.format(id)
self._redis.rpush('core:default', json.dumps(payload))
if self._redis.brpoplpush(flag, flag, DefaultTimeout) is None:
TimeoutError('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) | 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.
:param queue: command queue (commands on the same queue are executed sequentially)
:param max_time: kill job server side if it exceeded this amount of seconds
:param stream: If True, process stdout and stderr are pushed to a special queue (stream:<id>) so
client can stream output
:param tags: job tags
:param id: job id. Generated if not supplied
:return: Response object | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L3139-L3175 |
vallis/libstempo | libstempo/spharmORFbasis.py | calczeta | def calczeta(phi1, phi2, theta1, theta2):
"""
Calculate the angular separation between position (phi1, theta1) and
(phi2, theta2)
"""
zeta = 0.0
if phi1 == phi2 and theta1 == theta2:
zeta = 0.0
else:
argument = sin(theta1)*sin(theta2)*cos(phi1-phi2) + \
cos(theta1)*cos(theta2)
if argument < -1:
zeta = np.pi
elif argument > 1:
zeta = 0.0
else:
zeta = acos(argument)
return zeta | python | def calczeta(phi1, phi2, theta1, theta2):
"""
Calculate the angular separation between position (phi1, theta1) and
(phi2, theta2)
"""
zeta = 0.0
if phi1 == phi2 and theta1 == theta2:
zeta = 0.0
else:
argument = sin(theta1)*sin(theta2)*cos(phi1-phi2) + \
cos(theta1)*cos(theta2)
if argument < -1:
zeta = np.pi
elif argument > 1:
zeta = 0.0
else:
zeta = acos(argument)
return zeta | Calculate the angular separation between position (phi1, theta1) and
(phi2, theta2) | https://github.com/vallis/libstempo/blob/0b19300a9b24d64c9ddc25cd6ddbfd12b6231990/libstempo/spharmORFbasis.py#L23-L45 |
vallis/libstempo | libstempo/spharmORFbasis.py | dlmk | def dlmk(l,m,k,theta1):
"""
returns value of d^l_mk as defined in allen, ottewill 97.
Called by Dlmk
"""
if m >= k:
factor = sqrt(factorial(l-k)*factorial(l+m)/factorial(l+k)/factorial(l-m))
part2 = (cos(theta1/2))**(2*l+k-m)*(-sin(theta1/2))**(m-k)/factorial(m-k)
part3 = sp.hyp2f1(m-l,-k-l,m-k+1,-(tan(theta1/2))**2)
return factor*part2*part3
else:
return (-1)**(m-k) * dlmk(l,k,m,theta1) | python | def dlmk(l,m,k,theta1):
"""
returns value of d^l_mk as defined in allen, ottewill 97.
Called by Dlmk
"""
if m >= k:
factor = sqrt(factorial(l-k)*factorial(l+m)/factorial(l+k)/factorial(l-m))
part2 = (cos(theta1/2))**(2*l+k-m)*(-sin(theta1/2))**(m-k)/factorial(m-k)
part3 = sp.hyp2f1(m-l,-k-l,m-k+1,-(tan(theta1/2))**2)
return factor*part2*part3
else:
return (-1)**(m-k) * dlmk(l,k,m,theta1) | returns value of d^l_mk as defined in allen, ottewill 97.
Called by Dlmk | https://github.com/vallis/libstempo/blob/0b19300a9b24d64c9ddc25cd6ddbfd12b6231990/libstempo/spharmORFbasis.py#L173-L190 |
vallis/libstempo | libstempo/spharmORFbasis.py | Dlmk | def Dlmk(l,m,k,phi1,phi2,theta1,theta2):
"""
returns value of D^l_mk as defined in allen, ottewill 97.
"""
return exp(complex(0.,-m*phi1)) * dlmk(l,m,k,theta1) * \
exp(complex(0.,-k*gamma(phi1,phi2,theta1,theta2))) | python | def Dlmk(l,m,k,phi1,phi2,theta1,theta2):
"""
returns value of D^l_mk as defined in allen, ottewill 97.
"""
return exp(complex(0.,-m*phi1)) * dlmk(l,m,k,theta1) * \
exp(complex(0.,-k*gamma(phi1,phi2,theta1,theta2))) | returns value of D^l_mk as defined in allen, ottewill 97. | https://github.com/vallis/libstempo/blob/0b19300a9b24d64c9ddc25cd6ddbfd12b6231990/libstempo/spharmORFbasis.py#L193-L200 |
vallis/libstempo | libstempo/spharmORFbasis.py | gamma | def gamma(phi1,phi2,theta1,theta2):
"""
calculate third rotation angle
inputs are angles from 2 pulsars
returns the angle.
"""
if phi1 == phi2 and theta1 == theta2:
gamma = 0
else:
gamma = atan( sin(theta2)*sin(phi2-phi1) / \
(cos(theta1)*sin(theta2)*cos(phi1-phi2) - \
sin(theta1)*cos(theta2)) )
dummy_arg = (cos(gamma)*cos(theta1)*sin(theta2)*cos(phi1-phi2) + \
sin(gamma)*sin(theta2)*sin(phi2-phi1) - \
cos(gamma)*sin(theta1)*cos(theta2))
if dummy_arg >= 0:
return gamma
else:
return pi + gamma | python | def gamma(phi1,phi2,theta1,theta2):
"""
calculate third rotation angle
inputs are angles from 2 pulsars
returns the angle.
"""
if phi1 == phi2 and theta1 == theta2:
gamma = 0
else:
gamma = atan( sin(theta2)*sin(phi2-phi1) / \
(cos(theta1)*sin(theta2)*cos(phi1-phi2) - \
sin(theta1)*cos(theta2)) )
dummy_arg = (cos(gamma)*cos(theta1)*sin(theta2)*cos(phi1-phi2) + \
sin(gamma)*sin(theta2)*sin(phi2-phi1) - \
cos(gamma)*sin(theta1)*cos(theta2))
if dummy_arg >= 0:
return gamma
else:
return pi + gamma | calculate third rotation angle
inputs are angles from 2 pulsars
returns the angle. | https://github.com/vallis/libstempo/blob/0b19300a9b24d64c9ddc25cd6ddbfd12b6231990/libstempo/spharmORFbasis.py#L203-L225 |
vallis/libstempo | libstempo/spharmORFbasis.py | rotated_Gamma_ml | def rotated_Gamma_ml(m,l,phi1,phi2,theta1,theta2,gamma_ml):
"""
This function takes any gamma in the computational frame and rotates it to the
cosmic frame.
"""
rotated_gamma = 0
for ii in range(2*l+1):
rotated_gamma += Dlmk(l,m,ii-l,phi1,phi2,theta1,theta2).conjugate()*gamma_ml[ii]
return rotated_gamma | python | def rotated_Gamma_ml(m,l,phi1,phi2,theta1,theta2,gamma_ml):
"""
This function takes any gamma in the computational frame and rotates it to the
cosmic frame.
"""
rotated_gamma = 0
for ii in range(2*l+1):
rotated_gamma += Dlmk(l,m,ii-l,phi1,phi2,theta1,theta2).conjugate()*gamma_ml[ii]
return rotated_gamma | This function takes any gamma in the computational frame and rotates it to the
cosmic frame. | https://github.com/vallis/libstempo/blob/0b19300a9b24d64c9ddc25cd6ddbfd12b6231990/libstempo/spharmORFbasis.py#L266-L278 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.