Search is not available for this dataset
text
stringlengths
75
104k
def run(self, request, tempdir, opts): """ Constructs a command to run a cwl/json from requests and opts, runs it, and deposits the outputs in outdir. Runner: opts.getopt("runner", default="cwl-runner") CWL (url): request["workflow_url"] == a url to a cwl file or request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file) JSON File: request["workflow_params"] == input json text (to be written to a file) :param dict request: A dictionary containing the cwl/json information. :param wes_service.util.WESBackend opts: contains the user's arguments; specifically the runner and runner options :return: {"run_id": self.run_id, "state": state} """ with open(os.path.join(self.workdir, "request.json"), "w") as f: json.dump(request, f) with open(os.path.join(self.workdir, "cwl.input.json"), "w") as inputtemp: json.dump(request["workflow_params"], inputtemp) workflow_url = request.get("workflow_url") # Will always be local path to descriptor cwl, or url. output = open(os.path.join(self.workdir, "cwl.output.json"), "w") stderr = open(os.path.join(self.workdir, "stderr"), "w") runner = opts.getopt("runner", default="cwl-runner") extra = opts.getoptlist("extra") # replace any locally specified outdir with the default for e in extra: if e.startswith('--outdir='): extra.remove(e) extra.append('--outdir=' + self.outdir) # link the cwl and json into the tempdir/cwd if workflow_url.startswith('file://'): os.symlink(workflow_url[7:], os.path.join(tempdir, "wes_workflow.cwl")) workflow_url = os.path.join(tempdir, "wes_workflow.cwl") os.symlink(inputtemp.name, os.path.join(tempdir, "cwl.input.json")) jsonpath = os.path.join(tempdir, "cwl.input.json") # build args and run command_args = [runner] + extra + [workflow_url, jsonpath] proc = subprocess.Popen(command_args, stdout=output, stderr=stderr, close_fds=True, cwd=tempdir) output.close() stderr.close() with open(os.path.join(self.workdir, "pid"), "w") as pid: pid.write(str(proc.pid)) return self.getstatus()
def getstate(self): """ Returns RUNNING, -1 COMPLETE, 0 or EXECUTOR_ERROR, 255 """ state = "RUNNING" exit_code = -1 exitcode_file = os.path.join(self.workdir, "exit_code") pid_file = os.path.join(self.workdir, "pid") if os.path.exists(exitcode_file): with open(exitcode_file) as f: exit_code = int(f.read()) elif os.path.exists(pid_file): with open(pid_file, "r") as pid: pid = int(pid.read()) try: (_pid, exit_status) = os.waitpid(pid, os.WNOHANG) if _pid != 0: exit_code = exit_status >> 8 with open(exitcode_file, "w") as f: f.write(str(exit_code)) os.unlink(pid_file) except OSError: os.unlink(pid_file) exit_code = 255 if exit_code == 0: state = "COMPLETE" elif exit_code != -1: state = "EXECUTOR_ERROR" return state, exit_code
def write_workflow(self, request, opts, cwd, wftype='cwl'): """Writes a cwl, wdl, or python file as appropriate from the request dictionary.""" workflow_url = request.get("workflow_url") # link the cwl and json into the cwd if workflow_url.startswith('file://'): os.link(workflow_url[7:], os.path.join(cwd, "wes_workflow." + wftype)) workflow_url = os.path.join(cwd, "wes_workflow." + wftype) os.link(self.input_json, os.path.join(cwd, "wes_input.json")) self.input_json = os.path.join(cwd, "wes_input.json") extra_options = self.sort_toil_options(opts.getoptlist("extra")) if wftype == 'cwl': command_args = ['toil-cwl-runner'] + extra_options + [workflow_url, self.input_json] elif wftype == 'wdl': command_args = ['toil-wdl-runner'] + extra_options + [workflow_url, self.input_json] elif wftype == 'py': command_args = ['python'] + extra_options + [workflow_url] else: raise RuntimeError('workflow_type is not "cwl", "wdl", or "py": ' + str(wftype)) return command_args
def call_cmd(self, cmd, cwd): """ Calls a command with Popen. Writes stdout, stderr, and the command to separate files. :param cmd: A string or array of strings. :param tempdir: :return: The pid of the command. """ with open(self.cmdfile, 'w') as f: f.write(str(cmd)) stdout = open(self.outfile, 'w') stderr = open(self.errfile, 'w') logging.info('Calling: ' + ' '.join(cmd)) process = subprocess.Popen(cmd, stdout=stdout, stderr=stderr, close_fds=True, cwd=cwd) stdout.close() stderr.close() return process.pid
def run(self, request, tempdir, opts): """ Constructs a command to run a cwl/json from requests and opts, runs it, and deposits the outputs in outdir. Runner: opts.getopt("runner", default="cwl-runner") CWL (url): request["workflow_url"] == a url to a cwl file or request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file) JSON File: request["workflow_params"] == input json text (to be written to a file) :param dict request: A dictionary containing the cwl/json information. :param str tempdir: Folder where input files have been staged and the cwd to run at. :param wes_service.util.WESBackend opts: contains the user's arguments; specifically the runner and runner options :return: {"run_id": self.run_id, "state": state} """ wftype = request['workflow_type'].lower().strip() version = request['workflow_type_version'] if version != 'v1.0' and wftype == 'cwl': raise RuntimeError('workflow_type "cwl" requires ' '"workflow_type_version" to be "v1.0": ' + str(version)) if version != '2.7' and wftype == 'py': raise RuntimeError('workflow_type "py" requires ' '"workflow_type_version" to be "2.7": ' + str(version)) logging.info('Beginning Toil Workflow ID: ' + str(self.run_id)) with open(self.starttime, 'w') as f: f.write(str(time.time())) with open(self.request_json, 'w') as f: json.dump(request, f) with open(self.input_json, "w") as inputtemp: json.dump(request["workflow_params"], inputtemp) command_args = self.write_workflow(request, opts, tempdir, wftype=wftype) pid = self.call_cmd(command_args, tempdir) with open(self.endtime, 'w') as f: f.write(str(time.time())) with open(self.pidfile, 'w') as f: f.write(str(pid)) return self.getstatus()
def getstate(self): """ Returns QUEUED, -1 INITIALIZING, -1 RUNNING, -1 COMPLETE, 0 or EXECUTOR_ERROR, 255 """ # the jobstore never existed if not os.path.exists(self.jobstorefile): logging.info('Workflow ' + self.run_id + ': QUEUED') return "QUEUED", -1 # completed earlier if os.path.exists(self.statcompletefile): logging.info('Workflow ' + self.run_id + ': COMPLETE') return "COMPLETE", 0 # errored earlier if os.path.exists(self.staterrorfile): logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR') return "EXECUTOR_ERROR", 255 # the workflow is staged but has not run yet if not os.path.exists(self.errfile): logging.info('Workflow ' + self.run_id + ': INITIALIZING') return "INITIALIZING", -1 # TODO: Query with "toil status" completed = False with open(self.errfile, 'r') as f: for line in f: if 'Traceback (most recent call last)' in line: logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR') open(self.staterrorfile, 'a').close() return "EXECUTOR_ERROR", 255 # run can complete successfully but fail to upload outputs to cloud buckets # so save the completed status and make sure there was no error elsewhere if 'Finished toil run successfully.' in line: completed = True if completed: logging.info('Workflow ' + self.run_id + ': COMPLETE') open(self.statcompletefile, 'a').close() return "COMPLETE", 0 logging.info('Workflow ' + self.run_id + ': RUNNING') return "RUNNING", -1
def visit(d, op): """Recursively call op(d) for all list subelements and dictionary 'values' that d may have.""" op(d) if isinstance(d, list): for i in d: visit(i, op) elif isinstance(d, dict): for i in itervalues(d): visit(i, op)
def getopt(self, p, default=None): """Returns the first option value stored that matches p or default.""" for k, v in self.pairs: if k == p: return v return default
def getoptlist(self, p): """Returns all option values stored that match p as a list.""" optlist = [] for k, v in self.pairs: if k == p: optlist.append(v) return optlist
def catch_exceptions(orig_func): """Catch uncaught exceptions and turn them into http errors""" @functools.wraps(orig_func) def catch_exceptions_wrapper(self, *args, **kwargs): try: return orig_func(self, *args, **kwargs) except arvados.errors.ApiError as e: logging.exception("Failure") return {"msg": e._get_reason(), "status_code": e.resp.status}, int(e.resp.status) except subprocess.CalledProcessError as e: return {"msg": str(e), "status_code": 500}, 500 except MissingAuthorization: return {"msg": "'Authorization' header is missing or empty, expecting Arvados API token", "status_code": 401}, 401 except ValueError as e: return {"msg": str(e), "status_code": 400}, 400 except Exception as e: return {"msg": str(e), "status_code": 500}, 500 return catch_exceptions_wrapper
def _safe_name(file_name, sep): """Convert the file name to ASCII and normalize the string.""" file_name = stringify(file_name) if file_name is None: return file_name = ascii_text(file_name) file_name = category_replace(file_name, UNICODE_CATEGORIES) file_name = collapse_spaces(file_name) if file_name is None or not len(file_name): return return file_name.replace(WS, sep)
def safe_filename(file_name, sep='_', default=None, extension=None): """Create a secure filename for plain file system storage.""" if file_name is None: return decode_path(default) file_name = decode_path(file_name) file_name = os.path.basename(file_name) file_name, _extension = os.path.splitext(file_name) file_name = _safe_name(file_name, sep=sep) if file_name is None: return decode_path(default) file_name = file_name[:MAX_LENGTH] extension = _safe_name(extension or _extension, sep=sep) if extension is not None: file_name = '.'.join((file_name, extension)) file_name = file_name[:MAX_LENGTH] return file_name
def stringify(value, encoding_default='utf-8', encoding=None): """Brute-force convert a given object to a string. This will attempt an increasingly mean set of conversions to make a given object into a unicode string. It is guaranteed to either return unicode or None, if all conversions failed (or the value is indeed empty). """ if value is None: return None if not isinstance(value, six.text_type): if isinstance(value, (date, datetime)): return value.isoformat() elif isinstance(value, (float, Decimal)): return Decimal(value).to_eng_string() elif isinstance(value, six.binary_type): if encoding is None: encoding = guess_encoding(value, default=encoding_default) value = value.decode(encoding, 'replace') value = remove_byte_order_mark(value) value = remove_unsafe_chars(value) else: value = six.text_type(value) # XXX: is this really a good idea? value = value.strip() if not len(value): return None return value
def normalize_encoding(encoding, default=DEFAULT_ENCODING): """Normalize the encoding name, replace ASCII w/ UTF-8.""" if encoding is None: return default encoding = encoding.lower().strip() if encoding in ['', 'ascii']: return default try: codecs.lookup(encoding) return encoding except LookupError: return default
def normalize_result(result, default, threshold=0.2): """Interpret a chardet result.""" if result is None: return default if result.get('confidence') is None: return default if result.get('confidence') < threshold: return default return normalize_encoding(result.get('encoding'), default=default)
def guess_encoding(text, default=DEFAULT_ENCODING): """Guess string encoding. Given a piece of text, apply character encoding detection to guess the appropriate encoding of the text. """ result = chardet.detect(text) return normalize_result(result, default=default)
def guess_file_encoding(fh, default=DEFAULT_ENCODING): """Guess encoding from a file handle.""" start = fh.tell() detector = chardet.UniversalDetector() while True: data = fh.read(1024 * 10) if not data: detector.close() break detector.feed(data) if detector.done: break fh.seek(start) return normalize_result(detector.result, default=default)
def guess_path_encoding(file_path, default=DEFAULT_ENCODING): """Wrapper to open that damn file for you, lazy bastard.""" with io.open(file_path, 'rb') as fh: return guess_file_encoding(fh, default=default)
def decompose_nfkd(text): """Perform unicode compatibility decomposition. This will replace some non-standard value representations in unicode and normalise them, while also separating characters and their diacritics into two separate codepoints. """ if text is None: return None if not hasattr(decompose_nfkd, '_tr'): decompose_nfkd._tr = Transliterator.createInstance('Any-NFKD') return decompose_nfkd._tr.transliterate(text)
def compose_nfc(text): """Perform unicode composition.""" if text is None: return None if not hasattr(compose_nfc, '_tr'): compose_nfc._tr = Transliterator.createInstance('Any-NFC') return compose_nfc._tr.transliterate(text)
def category_replace(text, replacements=UNICODE_CATEGORIES): """Remove characters from a string based on unicode classes. This is a method for removing non-text characters (such as punctuation, whitespace, marks and diacritics) from a piece of text by class, rather than specifying them individually. """ if text is None: return None characters = [] for character in decompose_nfkd(text): cat = category(character) replacement = replacements.get(cat, character) if replacement is not None: characters.append(replacement) return u''.join(characters)
def remove_unsafe_chars(text): """Remove unsafe unicode characters from a piece of text.""" if isinstance(text, six.string_types): text = UNSAFE_RE.sub('', text) return text
def collapse_spaces(text): """Remove newlines, tabs and multiple spaces with single spaces.""" if not isinstance(text, six.string_types): return text return COLLAPSE_RE.sub(WS, text).strip(WS)
def normalize(text, lowercase=True, collapse=True, latinize=False, ascii=False, encoding_default='utf-8', encoding=None, replace_categories=UNICODE_CATEGORIES): """The main normalization function for text. This will take a string and apply a set of transformations to it so that it can be processed more easily afterwards. Arguments: * ``lowercase``: not very mysterious. * ``collapse``: replace multiple whitespace-like characters with a single whitespace. This is especially useful with category replacement which can lead to a lot of whitespace. * ``decompose``: apply a unicode normalization (NFKD) to separate simple characters and their diacritics. * ``replace_categories``: This will perform a replacement of whole classes of unicode characters (e.g. symbols, marks, numbers) with a given character. It is used to replace any non-text elements of the input string. """ text = stringify(text, encoding_default=encoding_default, encoding=encoding) if text is None: return if lowercase: # Yeah I made a Python package for this. text = text.lower() if ascii: # A stricter form of transliteration that leaves only ASCII # characters. text = ascii_text(text) elif latinize: # Perform unicode-based transliteration, e.g. of cyricllic # or CJK scripts into latin. text = latinize_text(text) if text is None: return # Perform unicode category-based character replacement. This is # used to filter out whole classes of characters, such as symbols, # punctuation, or whitespace-like characters. text = category_replace(text, replace_categories) if collapse: # Remove consecutive whitespace. text = collapse_spaces(text) return text
def slugify(text, sep='-'): """A simple slug generator.""" text = stringify(text) if text is None: return None text = text.replace(sep, WS) text = normalize(text, ascii=True) if text is None: return None return text.replace(WS, sep)
def latinize_text(text, ascii=False): """Transliterate the given text to the latin script. This attempts to convert a given text to latin script using the closest match of characters vis a vis the original script. """ if text is None or not isinstance(text, six.string_types) or not len(text): return text if ascii: if not hasattr(latinize_text, '_ascii'): # Transform to latin, separate accents, decompose, remove # symbols, compose, push to ASCII latinize_text._ascii = Transliterator.createInstance('Any-Latin; NFKD; [:Symbol:] Remove; [:Nonspacing Mark:] Remove; NFKC; Accents-Any; Latin-ASCII') # noqa return latinize_text._ascii.transliterate(text) if not hasattr(latinize_text, '_tr'): latinize_text._tr = Transliterator.createInstance('Any-Latin') return latinize_text._tr.transliterate(text)
def ascii_text(text): """Transliterate the given text and make sure it ends up as ASCII.""" text = latinize_text(text, ascii=True) if isinstance(text, six.text_type): text = text.encode('ascii', 'ignore').decode('ascii') return text
def message(self): """Return default message for this element """ if self.code != 200: for code in self.response_codes: if code.code == self.code: return code.message raise ValueError("Unknown response code \"%s\" in \"%s\"." % (self.code, self.name)) return "OK"
def get_default_sample(self): """Return default value for the element """ if self.type not in Object.Types or self.type is Object.Types.type: return self.type_object.get_sample() else: return self.get_object().get_sample()
def factory(cls, str_type, version): """Return a proper object """ type = Object.Types(str_type) if type is Object.Types.object: object = ObjectObject() elif type is Object.Types.array: object = ObjectArray() elif type is Object.Types.number: object = ObjectNumber() elif type is Object.Types.integer: object = ObjectInteger() elif type is Object.Types.string: object = ObjectString() elif type is Object.Types.boolean: object = ObjectBoolean() elif type is Object.Types.reference: object = ObjectReference() elif type is Object.Types.type: object = ObjectType() elif type is Object.Types.none: object = ObjectNone() elif type is Object.Types.dynamic: object = ObjectDynamic() elif type is Object.Types.const: object = ObjectConst() elif type is Object.Types.enum: object = ObjectEnum() else: object = Object() object.type = type object.version = version return object
def main(): """Main function to run command """ configParser = FileParser() logging.config.dictConfig( configParser.load_from_file(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings', 'logging.yml')) ) ApiDoc().main()
def _init_config(self): """return command's configuration from call's arguments """ options = self.parser.parse_args() if options.config is None and options.input is None: self.parser.print_help() sys.exit(2) if options.config is not None: configFactory = ConfigFactory() config = configFactory.load_from_file(options.config) else: config = ConfigObject() if options.input is not None: config["input"]["locations"] = [str(x) for x in options.input] if options.arguments is not None: config["input"]["arguments"] = dict((x.partition("=")[0], x.partition("=")[2]) for x in options.arguments) if options.output is not None: config["output"]["location"] = options.output if options.no_validate is not None: config["input"]["validate"] = not options.no_validate if options.dry_run is not None: self.dry_run = options.dry_run if options.watch is not None: self.watch = options.watch if options.traceback is not None: self.traceback = options.traceback if options.quiet is not None: self.logger.setLevel(logging.WARNING) if options.silence is not None: logging.disable(logging.CRITICAL) configService = ConfigService() configService.validate(config) self.config = config
def main(self): """Run the command """ self._init_config() if self.dry_run: return self.run_dry_run() elif self.watch: return self.run_watch() else: return self.run_render()
def _watch_refresh_source(self, event): """Refresh sources then templates """ self.logger.info("Sources changed...") try: self.sources = self._get_sources() self._render_template(self.sources) except: pass
def _watch_refresh_template(self, event): """Refresh template's contents """ self.logger.info("Template changed...") try: self._render_template(self.sources) except: pass
def add_property(attribute, type): """Add a property to a class """ def decorator(cls): """Decorator """ private = "_" + attribute def getAttr(self): """Property getter """ if getattr(self, private) is None: setattr(self, private, type()) return getattr(self, private) def setAttr(self, value): """Property setter """ setattr(self, private, value) setattr(cls, attribute, property(getAttr, setAttr)) setattr(cls, private, None) return cls return decorator
def _merge_files(self, input_files, output_file): """Combine the input files to a big output file""" # we assume that all the input files have the same charset with open(output_file, mode='wb') as out: for input_file in input_files: out.write(open(input_file, mode='rb').read())
def create_from_name_and_dictionary(self, name, datas): """Return a populated object Object from dictionary datas """ if "type" not in datas: str_type = "any" else: str_type = str(datas["type"]).lower() if str_type not in ObjectRaw.Types: type = ObjectRaw.Types("type") else: type = ObjectRaw.Types(str_type) if type is ObjectRaw.Types.object: object = ObjectObject() if "properties" in datas: object.properties = self.create_dictionary_of_element_from_dictionary("properties", datas) if "patternProperties" in datas: object.pattern_properties = self.create_dictionary_of_element_from_dictionary("patternProperties", datas) if "additionalProperties" in datas: if isinstance(datas["additionalProperties"], dict): object.additional_properties = self.create_from_name_and_dictionary("additionalProperties", datas["additionalProperties"]) elif not to_boolean(datas["additionalProperties"]): object.additional_properties = None else: raise ValueError("AdditionalProperties doe not allow empty value (yet)") elif type is ObjectRaw.Types.array: object = ObjectArray() if "items" in datas: object.items = self.create_from_name_and_dictionary("items", datas["items"]) else: object.items = ObjectObject() if "sample_count" in datas: object.sample_count = int(datas["sample_count"]) elif type is ObjectRaw.Types.number: object = ObjectNumber() elif type is ObjectRaw.Types.integer: object = ObjectInteger() elif type is ObjectRaw.Types.string: object = ObjectString() elif type is ObjectRaw.Types.boolean: object = ObjectBoolean() if "sample" in datas: object.sample = to_boolean(datas["sample"]) elif type is ObjectRaw.Types.reference: object = ObjectReference() if "reference" in datas: object.reference_name = str(datas["reference"]) elif type is ObjectRaw.Types.type: object = ObjectType() object.type_name = str(datas["type"]) elif type is ObjectRaw.Types.none: object = ObjectNone() elif type is ObjectRaw.Types.dynamic: object = ObjectDynamic() if "items" in datas: object.items = self.create_from_name_and_dictionary("items", datas["items"]) if "sample" in datas: if isinstance(datas["sample"], dict): object.sample = {} for k, v in datas["sample"].items(): object.sample[str(k)] = str(v) else: raise ValueError("A dictionnary is expected for dynamic\s object in \"%s\"" % name) elif type is ObjectRaw.Types.const: object = ObjectConst() if "const_type" in datas: const_type = str(datas["const_type"]) if const_type not in ObjectConst.Types: raise ValueError("Const type \"%s\" unknwon" % const_type) else: const_type = ObjectConst.Types.string object.const_type = const_type if "value" not in datas: raise ValueError("Missing const value") object.value = datas["value"] elif type is ObjectRaw.Types.enum: object = ObjectEnum() if "values" not in datas or not isinstance(datas['values'], list): raise ValueError("Missing enum values") object.values = [str(value) for value in datas["values"]] if "descriptions" in datas and isinstance(datas['descriptions'], dict): for (value_name, value_description) in datas["descriptions"].items(): value = EnumValue() value.name = value_name value.description = value_description object.descriptions.append(value) descriptions = [description.name for description in object.descriptions] for value_name in [x for x in object.values if x not in descriptions]: value = EnumValue() value.name = value_name object.descriptions.append(value) else: object = ObjectRaw() self.set_common_datas(object, name, datas) if isinstance(object, Constraintable): self.set_constraints(object, datas) object.type = type if "optional" in datas: object.optional = to_boolean(datas["optional"]) return object
def merge_extends(self, target, extends, inherit_key="inherit", inherit=False): """Merge extended dicts """ if isinstance(target, dict): if inherit and inherit_key in target and not to_boolean(target[inherit_key]): return if not isinstance(extends, dict): raise ValueError("Unable to merge: Dictionnary expected") for key in extends: if key not in target: target[str(key)] = extends[key] else: self.merge_extends(target[key], extends[key], inherit_key, True) elif isinstance(target, list): if not isinstance(extends, list): raise ValueError("Unable to merge: List expected") target += extends
def merge_sources(self, datas): """Merge sources files """ datas = [data for data in datas if data is not None] if len(datas) == 0: raise ValueError("Data missing") if len(datas) == 1: return datas[0] if isinstance(datas[0], list): if len([x for x in datas if not isinstance(x, list)]) > 0: raise TypeError("Unable to merge: List expected") base = [] for x in datas: base = base + x return base if isinstance(datas[0], dict): if len([x for x in datas if not isinstance(x, dict)]) > 0: raise TypeError("Unable to merge: Dictionnary expected") result = {} for element in datas: for key in element: if key in result: result[key] = self.merge_sources([result[key], element[key]]) else: result[key] = element[key] return result if len([x for x in datas if isinstance(x, (dict, list))]) > 0: raise TypeError("Unable to merge: List not expected") raise ValueError("Unable to merge: Conflict")
def merge_configs(self, config, datas): """Merge configs files """ if not isinstance(config, dict) or len([x for x in datas if not isinstance(x, dict)]) > 0: raise TypeError("Unable to merge: Dictionnary expected") for key, value in config.items(): others = [x[key] for x in datas if key in x] if len(others) > 0: if isinstance(value, dict): config[key] = self.merge_configs(value, others) else: config[key] = others[-1] return config
def factory(cls, object_raw): """Return a proper object """ if object_raw is None: return None if object_raw.type is ObjectRaw.Types.object: return ObjectObject(object_raw) elif object_raw.type is ObjectRaw.Types.type: return ObjectType(object_raw) elif object_raw.type is ObjectRaw.Types.array: return ObjectArray(object_raw) elif object_raw.type is ObjectRaw.Types.dynamic: return ObjectDynamic(object_raw) elif object_raw.type is ObjectRaw.Types.const: return ObjectConst(object_raw) elif object_raw.type is ObjectRaw.Types.enum: return ObjectEnum(object_raw) else: return Object(object_raw)
def render(self, sources, config, out=sys.stdout): """Render the documentation as defined in config Object """ logger = logging.getLogger() template = self.env.get_template(self.input) output = template.render(sources=sources, layout=config["output"]["layout"], config=config["output"]) if self.output == "stdout": out.write(output) else: dir = os.path.dirname(self.output) if dir and not os.path.exists(dir): try: os.makedirs(dir) except IOError as ioerror: logger.error('Error on creating dir "{}": {}'.format(dir, str(ioerror))) return if config["output"]["template"] == "default": if config["output"]["componants"] == "local": for template_dir in self.env.loader.searchpath: files = ( os.path.join(template_dir, "resource", "js", "combined.js"), os.path.join(template_dir, "resource", "css", "combined.css"), os.path.join(template_dir, "resource", "font", "apidoc.eot"), os.path.join(template_dir, "resource", "font", "apidoc.woff"), os.path.join(template_dir, "resource", "font", "apidoc.ttf"), os.path.join(template_dir, "resource", "font", "source-code-pro.eot"), os.path.join(template_dir, "resource", "font", "source-code-pro.woff"), os.path.join(template_dir, "resource", "font", "source-code-pro.ttf"), ) for file in files: filename = os.path.basename(file) dirname = os.path.basename(os.path.dirname(file)) if not os.path.exists(os.path.join(dir, dirname)): os.makedirs(os.path.join(dir, dirname)) if os.path.exists(file): shutil.copyfile(file, os.path.join(dir, dirname, filename)) else: logger.warn('Missing resource file "%s". If you run apidoc in virtualenv, run "%s"' % (filename, "python setup.py resources")) if config["output"]["componants"] == "remote": for template_dir in self.env.loader.searchpath: files = ( os.path.join(template_dir, "resource", "js", "combined.js"), os.path.join(template_dir, "resource", "css", "combined-embedded.css"), os.path.join(template_dir, "resource", "font", "apidoc.eot"), os.path.join(template_dir, "resource", "font", "apidoc.woff"), os.path.join(template_dir, "resource", "font", "apidoc.ttf"), os.path.join(template_dir, "resource", "font", "source-code-pro.eot"), os.path.join(template_dir, "resource", "font", "source-code-pro.woff"), os.path.join(template_dir, "resource", "font", "source-code-pro.ttf"), ) for file in files: filename = os.path.basename(file) dirname = os.path.basename(os.path.dirname(file)) if not os.path.exists(os.path.join(dir, dirname)): os.makedirs(os.path.join(dir, dirname)) if os.path.exists(file): shutil.copyfile(file, os.path.join(dir, dirname, filename)) else: logger.warn('Missing resource file "%s". If you run apidoc in virtualenv, run "%s"' % (filename, "python setup.py resources")) open(self.output, "w").write(output)
def create_from_dictionary(self, datas): """Return a populated object Configuration from dictionnary datas """ configuration = ObjectConfiguration() if "uri" in datas: configuration.uri = str(datas["uri"]) if "title" in datas: configuration.title = str(datas["title"]) if "description" in datas: configuration.description = str(datas["description"]) return configuration
def create_from_name_and_dictionary(self, name, datas): """Return a populated object Parameter from dictionary datas """ parameter = ObjectParameter() self.set_common_datas(parameter, name, datas) if "optional" in datas: parameter.optional = to_boolean(datas["optional"]) if "type" in datas: parameter.type = str(datas["type"]) if "generic" in datas: parameter.generic = to_boolean(datas["generic"]) return parameter
def validate(self, sources): """Validate the format of sources """ if not isinstance(sources, Root): raise Exception("Source object expected") parameters = self.get_uri_with_missing_parameters(sources) for parameter in parameters: logging.getLogger().warn('Missing parameter "%s" in uri of method "%s" in versions "%s"' % (parameter["name"], parameter["method"], parameter["version"]))
def validate(self, config): """Validate that the source file is ok """ if not isinstance(config, ConfigObject): raise Exception("Config object expected") if config["output"]["componants"] not in ("local", "remote", "embedded", "without"): raise ValueError("Unknown componant \"%s\"." % config["output"]["componants"]) if config["output"]["layout"] not in ("default", "content-only"): raise ValueError("Unknown layout \"%s\"." % config["output"]["layout"]) if config["input"]["locations"] is not None: unknown_locations = [x for x in config["input"]["locations"] if not os.path.exists(x)] if len(unknown_locations) > 0: raise ValueError( "Location%s \"%s\" does not exists" % ("s" if len(unknown_locations) > 1 else "", ("\" and \"").join(unknown_locations)) ) config["input"]["locations"] = [os.path.realpath(x) for x in config["input"]["locations"]] if config["input"]["arguments"] is not None: if not isinstance(config["input"]["arguments"], dict): raise ValueError( "Sources arguments \"%s\" are not a dict" % config["input"]["arguments"] )
def get_template_from_config(self, config): """Retrieve a template path from the config object """ if config["output"]["template"] == "default": return os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'template', 'default.html' ) else: return os.path.abspath(config["output"]["template"])
def create_from_dictionary(self, datas): """Return a populated object ResponseCode from dictionary datas """ if "code" not in datas: raise ValueError("A response code must contain a code in \"%s\"." % repr(datas)) code = ObjectResponseCode() self.set_common_datas(code, str(datas["code"]), datas) code.code = int(datas["code"]) if "message" in datas: code.message = str(datas["message"]) elif code.code in self.default_messages.keys(): code.message = self.default_messages[code.code] if "generic" in datas: code.generic = to_boolean(datas["generic"]) return code
def add_handler(self, path, handler): """Add a path in watch queue """ self.signatures[path] = self.get_path_signature(path) self.handlers[path] = handler
def get_path_signature(self, path): """generate a unique signature for file contained in path """ if not os.path.exists(path): return None if os.path.isdir(path): merge = {} for root, dirs, files in os.walk(path): for name in files: full_name = os.path.join(root, name) merge[full_name] = os.stat(full_name) return merge else: return os.stat(path)
def check(self): """Check if a file is changed """ for (path, handler) in self.handlers.items(): current_signature = self.signatures[path] new_signature = self.get_path_signature(path) if new_signature != current_signature: self.signatures[path] = new_signature handler.on_change(Event(path))
def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (int(self.major), int(self.minor), str(self.label), str(self.name))
def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (int(self.order), str(self.label), str(self.name))
def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (not self.generic, str(self.name), str(self.description))
def get_comparable_values_for_ordering(self): """Return a tupple of values representing the unicity of the object """ return (0 if self.position >= 0 else 1, int(self.position), str(self.name), str(self.description))
def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (not self.generic, int(self.code), str(self.message), str(self.description))
def factory(cls, object_source): """Return a proper object """ if object_source.type is ObjectRaw.Types.object: return ObjectObject(object_source) elif object_source.type not in ObjectRaw.Types or object_source.type is ObjectRaw.Types.type: return ObjectType(object_source) elif object_source.type is ObjectRaw.Types.array: return ObjectArray(object_source) elif object_source.type is ObjectRaw.Types.dynamic: return ObjectDynamic(object_source) elif object_source.type is ObjectRaw.Types.const: return ObjectConst(object_source) elif object_source.type is ObjectRaw.Types.enum: return ObjectEnum(object_source) else: return Object(object_source)
def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (str(self.name), str(self.description), str(self.type), bool(self.optional), str(self.constraints) if isinstance(self, Constraintable) else "")
def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (str(self.name), str(self.description), str(self.constraints))
def create_from_name_and_dictionary(self, name, datas): """Return a populated object Category from dictionary datas """ category = ObjectCategory(name) self.set_common_datas(category, name, datas) if "order" in datas: category.order = int(datas["order"]) return category
def load_from_file(self, file_path, format=None): """Return dict from a file config """ if format is None: base_name, file_extension = os.path.splitext(file_path) if file_extension in (".yaml", ".yml"): format = "yaml" elif file_extension in (".json"): format = "json" else: raise ValueError("Config file \"%s\" undetermined" % file_extension) if format == "yaml": return yaml.load(open(file_path), Loader=yaml.CSafeLoader if yaml.__with_libyaml__ else yaml.SafeLoader) elif format == "json": return json.load(open(file_path)) else: raise ValueError("Format \"%s\" unknwon" % format)
def load_all_from_directory(self, directory_path): """Return a list of dict from a directory containing files """ datas = [] for root, folders, files in os.walk(directory_path): for f in files: datas.append(self.load_from_file(os.path.join(root, f))) return datas
def json_repr(obj): """Represent instance of a class as JSON. """ def serialize(obj): """Recursively walk object's hierarchy. """ if obj is None: return None if isinstance(obj, Enum): return str(obj) if isinstance(obj, (bool, int, float, str)): return obj if isinstance(obj, dict): obj = obj.copy() for key in sorted(obj.keys()): obj[key] = serialize(obj[key]) return obj if isinstance(obj, list): return [serialize(item) for item in obj] if isinstance(obj, tuple): return tuple(serialize([item for item in obj])) if hasattr(obj, '__dict__'): return serialize(obj.__dict__) return repr(obj) return json.dumps(serialize(obj))
def create_from_root(self, root_source): """Return a populated Object Root from dictionnary datas """ root_dto = ObjectRoot() root_dto.configuration = root_source.configuration root_dto.versions = [Version(x) for x in root_source.versions.values()] for version in sorted(root_source.versions.values()): hydrator = Hydrator(version, root_source.versions, root_source.versions[version.name].types) for method in version.methods.values(): hydrator.hydrate_method(root_dto, root_source, method) for type in version.types.values(): hydrator.hydrate_type(root_dto, root_source, type) self.define_changes_status(root_dto) return root_dto
def set_common_datas(self, element, name, datas): """Populated common data for an element from dictionnary datas """ element.name = str(name) if "description" in datas: element.description = str(datas["description"]).strip() if isinstance(element, Sampleable) and element.sample is None and "sample" in datas: element.sample = str(datas["sample"]).strip() if isinstance(element, Displayable): if "display" in datas: element.display = to_boolean(datas["display"]) if "label" in datas: element.label = datas["label"] else: element.label = element.name
def create_dictionary_of_element_from_dictionary(self, property_name, datas): """Populate a dictionary of elements """ response = {} if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], collections.Iterable): for key, value in datas[property_name].items(): response[key] = self.create_from_name_and_dictionary(key, value) return response
def create_list_of_element_from_dictionary(self, property_name, datas): """Populate a list of elements """ response = [] if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], list): for value in datas[property_name]: response.append(self.create_from_dictionary(value)) return response
def get_enum(self, property, enum, datas): """Factory enum type """ str_property = str(datas[property]).lower() if str_property not in enum: raise ValueError("Unknow enum \"%s\" for \"%s\"." % (str_property, property)) return enum(str_property)
def create_from_config(self, config): """Create a template object file defined in the config object """ configService = ConfigService() template = TemplateService() template.output = config["output"]["location"] template_file = configService.get_template_from_config(config) template.input = os.path.basename(template_file) template.env = Environment(loader=FileSystemLoader(os.path.dirname(template_file))) return template
def deploy(self, id_networkv4): """Deploy network in equipments and set column 'active = 1' in tables redeipv4 :param id_networkv4: ID for NetworkIPv4 :return: Equipments configuration output """ data = dict() uri = 'api/networkv4/%s/equipments/' % id_networkv4 return super(ApiNetworkIPv4, self).post(uri, data=data)
def get_by_id(self, id_networkv4): """Get IPv4 network :param id_networkv4: ID for NetworkIPv4 :return: IPv4 Network """ uri = 'api/networkv4/%s/' % id_networkv4 return super(ApiNetworkIPv4, self).get(uri)
def list(self, environment_vip=None): """List IPv4 networks :param environment_vip: environment vip to filter :return: IPv4 Networks """ uri = 'api/networkv4/?' if environment_vip: uri += 'environment_vip=%s' % environment_vip return super(ApiNetworkIPv4, self).get(uri)
def undeploy(self, id_networkv4): """Remove deployment of network in equipments and set column 'active = 0' in tables redeipv4 ] :param id_networkv4: ID for NetworkIPv4 :return: Equipments configuration output """ uri = 'api/networkv4/%s/equipments/' % id_networkv4 return super(ApiNetworkIPv4, self).delete(uri)
def check_vip_ip(self, ip, environment_vip): """ Check available ip in environment vip """ uri = 'api/ipv4/ip/%s/environment-vip/%s/' % (ip, environment_vip) return super(ApiNetworkIPv4, self).get(uri)
def delete_ipv4(self, ipv4_id): """ Delete ipv4 """ uri = 'api/ipv4/%s/' % (ipv4_id) return super(ApiNetworkIPv4, self).delete(uri)
def search(self, **kwargs): """ Method to search ipv4's based on extends search. :param search: Dict containing QuerySets to find ipv4's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing ipv4's """ return super(ApiNetworkIPv4, self).get(self.prepare_url('api/v3/networkv4/', kwargs))
def delete(self, ids): """ Method to delete network-ipv4's by their ids :param ids: Identifiers of network-ipv4's :return: None """ url = build_uri_with_ids('api/v3/networkv4/%s/', ids) return super(ApiNetworkIPv4, self).delete(url)
def update(self, networkipv4s): """ Method to update network-ipv4's :param networkipv4s: List containing network-ipv4's desired to updated :return: None """ data = {'networks': networkipv4s} networkipv4s_ids = [str(networkipv4.get('id')) for networkipv4 in networkipv4s] return super(ApiNetworkIPv4, self).put('api/v3/networkv4/%s/' % ';'.join(networkipv4s_ids), data)
def create(self, networkipv4s): """ Method to create network-ipv4's :param networkipv4s: List containing networkipv4's desired to be created on database :return: None """ data = {'networks': networkipv4s} return super(ApiNetworkIPv4, self).post('api/v3/networkv4/', data)
def inserir(self, name): """Inserts a new Division Dc and returns its identifier. :param name: Division Dc name. String with a minimum 2 and maximum of 80 characters :return: Dictionary with the following structure: :: {'division_dc': {'id': < id_division_dc >}} :raise InvalidParameterError: Name is null and invalid. :raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ division_dc_map = dict() division_dc_map['name'] = name code, xml = self.submit( {'division_dc': division_dc_map}, 'POST', 'divisiondc/') return self.response(code, xml)
def alterar(self, id_divisiondc, name): """Change Division Dc from by the identifier. :param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero. :param name: Division Dc name. String with a minimum 2 and maximum of 80 characters :return: None :raise InvalidParameterError: The identifier of Division Dc or name is null and invalid. :raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name. :raise DivisaoDcNaoExisteError: Division Dc not registered. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ if not is_valid_int_param(id_divisiondc): raise InvalidParameterError( u'The identifier of Division Dc is invalid or was not informed.') url = 'divisiondc/' + str(id_divisiondc) + '/' division_dc_map = dict() division_dc_map['name'] = name code, xml = self.submit({'division_dc': division_dc_map}, 'PUT', url) return self.response(code, xml)
def remover(self, id_divisiondc): """Remove Division Dc from by the identifier. :param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero. :return: None :raise InvalidParameterError: The identifier of Division Dc is null and invalid. :raise DivisaoDcNaoExisteError: Division Dc not registered. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ if not is_valid_int_param(id_divisiondc): raise InvalidParameterError( u'The identifier of Division Dc is invalid or was not informed.') url = 'divisiondc/' + str(id_divisiondc) + '/' code, xml = self.submit(None, 'DELETE', url) return self.response(code, xml)
def search(self, **kwargs): """ Method to search object types based on extends search. :param search: Dict containing QuerySets to find object types. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing object types """ return super(ApiObjectType, self).get(self.prepare_url('api/v3/object-type/', kwargs))
def find_vlans( self, number, name, iexact, environment, net_type, network, ip_version, subnet, acl, pagination): """ Find vlans by all search parameters :param number: Filter by vlan number column :param name: Filter by vlan name column :param iexact: Filter by name will be exact? :param environment: Filter by environment ID related :param net_type: Filter by network_type ID related :param network: Filter by each octs in network :param ip_version: Get only version (0:ipv4, 1:ipv6, 2:all) :param subnet: Filter by octs will search by subnets? :param acl: Filter by vlan acl column :param pagination: Class with all data needed to paginate :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_ambiente': < id_ambiente >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'acl_file_name_v6': < acl_file_name_v6 >, 'acl_valida_v6': < acl_valida_v6 >, 'ativada': < ativada >, 'ambiente_name': < divisao_dc-ambiente_logico-grupo_l3 > 'redeipv4': [ { all networkipv4 related } ], 'redeipv6': [ { all networkipv6 related } ] }, 'total': {< total_registros >} } :raise InvalidParameterError: Some parameter was invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ if not isinstance(pagination, Pagination): raise InvalidParameterError( u"Invalid parameter: pagination must be a class of type 'Pagination'.") vlan_map = dict() vlan_map['start_record'] = pagination.start_record vlan_map['end_record'] = pagination.end_record vlan_map['asorting_cols'] = pagination.asorting_cols vlan_map['searchable_columns'] = pagination.searchable_columns vlan_map['custom_search'] = pagination.custom_search vlan_map['numero'] = number vlan_map['nome'] = name vlan_map['exato'] = iexact vlan_map['ambiente'] = environment vlan_map['tipo_rede'] = net_type vlan_map['rede'] = network vlan_map['versao'] = ip_version vlan_map['subrede'] = subnet vlan_map['acl'] = acl url = 'vlan/find/' code, xml = self.submit({'vlan': vlan_map}, 'POST', url) key = 'vlan' return get_list_map( self.response( code, xml, [ key, 'redeipv4', 'redeipv6', 'equipamentos']), key)
def listar_por_ambiente(self, id_ambiente): """List all VLANs from an environment. ** The itens returning from network is there to be compatible with other system ** :param id_ambiente: Environment identifier. :return: Following dictionary: :: {'vlan': [{'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'ambiente': < id_ambiente >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'acl_file_name_v6': < acl_file_name_v6 >, 'acl_valida_v6': < acl_valida_v6 >, 'ativada': < ativada >, 'id_tipo_rede': < id_tipo_rede >, 'rede_oct1': < rede_oct1 >, 'rede_oct2': < rede_oct2 >, 'rede_oct3': < rede_oct3 >, 'rede_oct4': < rede_oct4 >, 'bloco': < bloco >, 'mascara_oct1': < mascara_oct1 >, 'mascara_oct2': < mascara_oct2 >, 'mascara_oct3': < mascara_oct3 >, 'mascara_oct4': < mascara_oct4 >, 'broadcast': < broadcast >,} , ... other vlans ... ]} :raise InvalidParameterError: Environment id is none or invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ if not is_valid_int_param(id_ambiente): raise InvalidParameterError(u'Environment id is none or invalid.') url = 'vlan/ambiente/' + str(id_ambiente) + '/' code, xml = self.submit(None, 'GET', url) key = 'vlan' return get_list_map(self.response(code, xml, [key]), key)
def alocar( self, nome, id_tipo_rede, id_ambiente, descricao, id_ambiente_vip=None, vrf=None): """Inserts a new VLAN. :param nome: Name of Vlan. String with a maximum of 50 characters. :param id_tipo_rede: Identifier of the Network Type. Integer value and greater than zero. :param id_ambiente: Identifier of the Environment. Integer value and greater than zero. :param descricao: Description of Vlan. String with a maximum of 200 characters. :param id_ambiente_vip: Identifier of the Environment Vip. Integer value and greater than zero. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_tipo_rede': < id_tipo_rede >, 'id_ambiente': < id_ambiente >, 'rede_oct1': < rede_oct1 >, 'rede_oct2': < rede_oct2 >, 'rede_oct3': < rede_oct3 >, 'rede_oct4': < rede_oct4 >, 'bloco': < bloco >, 'mascara_oct1': < mascara_oct1 >, 'mascara_oct2': < mascara_oct2 >, 'mascara_oct3': < mascara_oct3 >, 'mascara_oct4': < mascara_oct4 >, 'broadcast': < broadcast >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'ativada': < ativada >}} :raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available. :raise VlanNaoExisteError: VLAN not found. :raise TipoRedeNaoExisteError: Network Type not registered. :raise AmbienteNaoExisteError: Environment not registered. :raise EnvironmentVipNotFoundError: Environment VIP not registered. :raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid. :raise IPNaoDisponivelError: There is no network address is available to create the VLAN. :raise ConfigEnvironmentInvalidError: Invalid Environment Configuration or not registered :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ vlan_map = dict() vlan_map['nome'] = nome vlan_map['id_tipo_rede'] = id_tipo_rede vlan_map['id_ambiente'] = id_ambiente vlan_map['descricao'] = descricao vlan_map['id_ambiente_vip'] = id_ambiente_vip vlan_map['vrf'] = vrf code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/') return self.response(code, xml)
def insert_vlan( self, environment_id, name, number, description, acl_file, acl_file_v6, network_ipv4, network_ipv6, vrf=None): """Create new VLAN :param environment_id: ID for Environment. :param name: The name of VLAN. :param description: Some description to VLAN. :param number: Number of Vlan :param acl_file: Acl IPv4 File name to VLAN. :param acl_file_v6: Acl IPv6 File name to VLAN. :param network_ipv4: responsible for generating a network attribute ipv4 automatically. :param network_ipv6: responsible for generating a network attribute ipv6 automatically. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_ambiente': < id_ambiente >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'ativada': < ativada > 'acl_file_name_v6': < acl_file_name_v6 >, 'acl_valida_v6': < acl_valida_v6 >, } } :raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available. :raise VlanNaoExisteError: VLAN not found. :raise AmbienteNaoExisteError: Environment not registered. :raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ if not is_valid_int_param(environment_id): raise InvalidParameterError(u'Environment id is none or invalid.') if not is_valid_int_param(number): raise InvalidParameterError(u'Vlan number is none or invalid') vlan_map = dict() vlan_map['environment_id'] = environment_id vlan_map['name'] = name vlan_map['description'] = description vlan_map['acl_file'] = acl_file vlan_map['acl_file_v6'] = acl_file_v6 vlan_map['number'] = number vlan_map['network_ipv4'] = network_ipv4 vlan_map['network_ipv6'] = network_ipv6 vlan_map['vrf'] = vrf code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/insert/') return self.response(code, xml)
def edit_vlan( self, environment_id, name, number, description, acl_file, acl_file_v6, id_vlan): """Edit a VLAN :param id_vlan: ID for Vlan :param environment_id: ID for Environment. :param name: The name of VLAN. :param description: Some description to VLAN. :param number: Number of Vlan :param acl_file: Acl IPv4 File name to VLAN. :param acl_file_v6: Acl IPv6 File name to VLAN. :return: None :raise VlanError: VLAN name already exists, DC division of the environment invalid or there is no VLAN number available. :raise VlanNaoExisteError: VLAN not found. :raise AmbienteNaoExisteError: Environment not registered. :raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'Vlan id is invalid or was not informed.') if not is_valid_int_param(environment_id): raise InvalidParameterError(u'Environment id is none or invalid.') if not is_valid_int_param(number): raise InvalidParameterError(u'Vlan number is none or invalid') vlan_map = dict() vlan_map['vlan_id'] = id_vlan vlan_map['environment_id'] = environment_id vlan_map['name'] = name vlan_map['description'] = description vlan_map['acl_file'] = acl_file vlan_map['acl_file_v6'] = acl_file_v6 vlan_map['number'] = number code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/edit/') return self.response(code, xml)
def create_vlan(self, id_vlan): """ Set column 'ativada = 1'. :param id_vlan: VLAN identifier. :return: None """ vlan_map = dict() vlan_map['vlan_id'] = id_vlan code, xml = self.submit({'vlan': vlan_map}, 'PUT', 'vlan/create/') return self.response(code, xml)
def allocate_without_network(self, environment_id, name, description, vrf=None): """Create new VLAN without add NetworkIPv4. :param environment_id: ID for Environment. :param name: The name of VLAN. :param description: Some description to VLAN. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_ambiente': < id_ambiente >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'acl_file_name_v6': < acl_file_name_v6 >, 'acl_valida_v6': < acl_valida_v6 >, 'ativada': < ativada > } } :raise VlanError: Duplicate name of VLAN, division DC of Environment not found/invalid or VLAN number not available. :raise AmbienteNaoExisteError: Environment not found. :raise InvalidParameterError: Some parameter was invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ vlan_map = dict() vlan_map['environment_id'] = environment_id vlan_map['name'] = name vlan_map['description'] = description vlan_map['vrf'] = vrf code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/no-network/') return self.response(code, xml)
def verificar_permissao(self, id_vlan, nome_equipamento, nome_interface): """Check if there is communication permission for VLAN to trunk. Run script 'configurador'. The "stdout" key value of response dictionary is 1(one) if VLAN has permission, or 0(zero), otherwise. :param id_vlan: VLAN identifier. :param nome_equipamento: Equipment name. :param nome_interface: Interface name. :return: Following dictionary: :: {‘sucesso’: {‘codigo’: < codigo >, ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}} :raise VlanNaoExisteError: VLAN does not exist. :raise InvalidParameterError: VLAN id is none or invalid. :raise InvalidParameterError: Equipment name and/or interface name is invalid or none. :raise EquipamentoNaoExisteError: Equipment does not exist. :raise LigacaoFrontInterfaceNaoExisteError: There is no interface on front link of informed interface. :raise InterfaceNaoExisteError: Interface does not exist or is not associated to equipment. :raise LigacaoFrontNaoTerminaSwitchError: Interface does not have switch connected. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. :raise ScriptError: Failed to run the script. """ if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'Vlan id is invalid or was not informed.') url = 'vlan/' + str(id_vlan) + '/check/' vlan_map = dict() vlan_map['nome'] = nome_equipamento vlan_map['nome_interface'] = nome_interface code, xml = self.submit({'equipamento': vlan_map}, 'PUT', url) return self.response(code, xml)
def buscar(self, id_vlan): """Get VLAN by its identifier. :param id_vlan: VLAN identifier. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_ambiente': < id_ambiente >, 'id_tipo_rede': < id_tipo_rede >, 'rede_oct1': < rede_oct1 >, 'rede_oct2': < rede_oct2 >, 'rede_oct3': < rede_oct3 >, 'rede_oct4': < rede_oct4 >, 'bloco': < bloco >, 'mascara_oct1': < mascara_oct1 >, 'mascara_oct2': < mascara_oct2 >, 'mascara_oct3': < mascara_oct3 >, 'mascara_oct4': < mascara_oct4 >, 'broadcast': < broadcast >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'ativada': < ativada >} OR {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_tipo_rede': < id_tipo_rede >, 'id_ambiente': < id_ambiente >, 'bloco1': < bloco1 >, 'bloco2': < bloco2 >, 'bloco3': < bloco3 >, 'bloco4': < bloco4 >, 'bloco5': < bloco5 >, 'bloco6': < bloco6 >, 'bloco7': < bloco7 >, 'bloco8': < bloco8 >, 'bloco': < bloco >, 'mask_bloco1': < mask_bloco1 >, 'mask_bloco2': < mask_bloco2 >, 'mask_bloco3': < mask_bloco3 >, 'mask_bloco4': < mask_bloco4 >, 'mask_bloco5': < mask_bloco5 >, 'mask_bloco6': < mask_bloco6 >, 'mask_bloco7': < mask_bloco7 >, 'mask_bloco8': < mask_bloco8 >, 'broadcast': < broadcast >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'acl_file_name_v6': < acl_file_name_v6 >, 'acl_valida_v6': < acl_valida_v6 >, 'ativada': < ativada >}} :raise VlanNaoExisteError: VLAN does not exist. :raise InvalidParameterError: VLAN id is none or invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'Vlan id is invalid or was not informed.') url = 'vlan/' + str(id_vlan) + '/' code, xml = self.submit(None, 'GET', url) return self.response(code, xml)
def get(self, id_vlan): """Get a VLAN by your primary key. Network IPv4/IPv6 related will also be fetched. :param id_vlan: ID for VLAN. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_ambiente': < id_ambiente >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'acl_file_name_v6': < acl_file_name_v6 >, 'acl_valida_v6': < acl_valida_v6 >, 'ativada': < ativada >, 'redeipv4': [ { all networkipv4 related } ], 'redeipv6': [ { all networkipv6 related } ] } } :raise InvalidParameterError: Invalid ID for VLAN. :raise VlanNaoExisteError: VLAN not found. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'Parameter id_vlan is invalid. Value: ' + id_vlan) url = 'vlan/' + str(id_vlan) + '/network/' code, xml = self.submit(None, 'GET', url) return get_list_map( self.response( code, xml, [ 'redeipv4', 'redeipv6']), 'vlan')
def listar_permissao(self, nome_equipamento, nome_interface): """List all VLANS having communication permission to trunk from a port in switch. Run script 'configurador'. :: The value of 'stdout' key of return dictionary can have a list of numbers or number intervals of VLAN´s, comma separated. Examples of possible returns of 'stdout' below: - 100,103,111,... - 100-110,... - 100-110,112,115,... - 100,103,105-111,113,115-118,... :param nome_equipamento: Equipment name. :param nome_interface: Interface name. :return: Following dictionary: :: {‘sucesso’: {‘codigo’: < codigo >, ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}} :raise InvalidParameterError: Equipment name and/or interface name is invalid or none. :raise EquipamentoNaoExisteError: Equipment does not exist. :raise LigacaoFrontInterfaceNaoExisteError: There is no interface on front link of informed interface. :raise InterfaceNaoExisteError: Interface does not exist or is not associated to equipment. :raise LigacaoFrontNaoTerminaSwitchError: Interface does not have switch connected. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. :raise ScriptError: Failed to run the script. """ vlan_map = dict() vlan_map['nome'] = nome_equipamento vlan_map['nome_interface'] = nome_interface code, xml = self.submit({'equipamento': vlan_map}, 'PUT', 'vlan/list/') return self.response(code, xml)
def create_ipv4(self, id_network_ipv4): """Create VLAN in layer 2 using script 'navlan'. :param id_network_ipv4: NetworkIPv4 ID. :return: Following dictionary: :: {‘sucesso’: {‘codigo’: < codigo >, ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}} :raise NetworkIPv4NaoExisteError: NetworkIPv4 not found. :raise EquipamentoNaoExisteError: Equipament in list not found. :raise VlanError: VLAN is active. :raise InvalidParameterError: VLAN identifier is none or invalid. :raise InvalidParameterError: Equipment list is none or empty. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. :raise ScriptError: Failed to run the script. """ url = 'vlan/v4/create/' vlan_map = dict() vlan_map['id_network_ip'] = id_network_ipv4 code, xml = self.submit({'vlan': vlan_map}, 'POST', url) return self.response(code, xml)
def create_ipv6(self, id_network_ipv6): """Create VLAN in layer 2 using script 'navlan'. :param id_network_ipv6: NetworkIPv6 ID. :return: Following dictionary: :: {‘sucesso’: {‘codigo’: < codigo >, ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}} :raise NetworkIPv6NaoExisteError: NetworkIPv6 not found. :raise EquipamentoNaoExisteError: Equipament in list not found. :raise VlanError: VLAN is active. :raise InvalidParameterError: VLAN identifier is none or invalid. :raise InvalidParameterError: Equipment list is none or empty. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. :raise ScriptError: Failed to run the script. """ url = 'vlan/v6/create/' vlan_map = dict() vlan_map['id_network_ip'] = id_network_ipv6 code, xml = self.submit({'vlan': vlan_map}, 'POST', url) return self.response(code, xml)
def apply_acl(self, equipments, vlan, environment, network): '''Apply the file acl in equipments :param equipments: list of equipments :param vlan: Vvlan :param environment: Environment :param network: v4 or v6 :raise Exception: Failed to apply acl :return: True case Apply and sysout of script ''' vlan_map = dict() vlan_map['equipments'] = equipments vlan_map['vlan'] = vlan vlan_map['environment'] = environment vlan_map['network'] = network url = 'vlan/apply/acl/' code, xml = self.submit({'vlan': vlan_map}, 'POST', url) return self.response(code, xml)
def confirm_vlan(self, number_net, id_environment_vlan, ip_version=None): """Checking if the vlan insert need to be confirmed :param number_net: Filter by vlan number column :param id_environment_vlan: Filter by environment ID related :param ip_version: Ip version for checking :return: True is need confirmation, False if no need :raise AmbienteNaoExisteError: Ambiente não cadastrado. :raise InvalidParameterError: Invalid ID for VLAN. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ url = 'vlan/confirm/' + \ str(number_net) + '/' + id_environment_vlan + '/' + str(ip_version) code, xml = self.submit(None, 'GET', url) return self.response(code, xml)
def check_number_available(self, id_environment, num_vlan, id_vlan): """Checking if environment has a number vlan available :param id_environment: Identifier of environment :param num_vlan: Vlan number :param id_vlan: Vlan indentifier (False if inserting a vlan) :return: True is has number available, False if hasn't :raise AmbienteNaoExisteError: Ambiente não cadastrado. :raise InvalidParameterError: Invalid ID for VLAN. :raise VlanNaoExisteError: VLAN not found. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ url = 'vlan/check_number_available/' + \ str(id_environment) + '/' + str(num_vlan) + '/' + str(id_vlan) code, xml = self.submit(None, 'GET', url) return self.response(code, xml)